【Java】 Scanner類的幾個方法


  通過 Scanner 類可以獲取用戶的輸入,創建 Scanner 對象的基本語法如下:

Scanner sc = new Scanner(System.in);

 

nextInt()、next()和nextLine()

  nextInt(): it only reads the int value, nextInt() places the cursor(光標) in the same line after reading the input.(nextInt()只讀取數值,剩下”\n”還沒有讀取,並將cursor放在本行中)

  next(): read the input only till the space. It can’t read two words separated by space. Also, next() places the cursor in the same line after reading the input.(next()只讀空格之前的數據,並且cursor指向本行) 
  next() 方法遇見第一個有效字符(非空格,非換行符)時,開始掃描,當遇見第一個分隔符或結束符(空格或換行符)時,結束掃描,獲取掃描到的內容,即獲得第一個掃描到的不含空格、換行符的單個字符串。

  nextLine(): reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line. 
  nextLine()時,則可以掃描到一行內容並作為一個字符串而被獲取到。

 

public class NextTest{  
    public static void main(String[] args) {  
        String s1,s2;  
        Scanner sc=new Scanner(System.in);  
        System.out.print("請輸入第一個字符串:");  
        s1=sc.nextLine();  
        System.out.print("請輸入第二個字符串:");  
        s2=sc.next();  
        System.out.println("輸入的字符串是:"+s1+" "+s2);  
    }  
}  

  

請輸入第一個字符串:abc
請輸入第二個字符串:def
輸入的字符串是:abc def
View Code

 

//s1、s2交換
public class NextTest {
	    public static void main(String[] args) {  
	        String s1,s2;  
	        Scanner sc=new Scanner(System.in);  
	        System.out.print("請輸入第一個字符串:");  
	        s1=sc.next();  
	        System.out.print("請輸入第二個字符串:");  
	        s2=sc.nextLine();  
	        System.out.println("輸入的字符串是:"+s1+" "+s2);  
	    }  
}

  

請輸入第一個字符串:abc
請輸入第二個字符串:輸入的字符串是:abc 
View Code

 

  nextLine()自動讀取了被next()去掉的Enter作為他的結束符,所以沒辦法給s2從鍵盤輸入值。

  如double nextDouble() , float nextFloat() , int nextInt() 等與nextLine()連用時都存在這個問題,解決的辦法是:在每一個 next()、nextDouble() 、 nextFloat()、nextInt() 等語句之后加一個nextLine()語句,將被next()去掉的Enter結束符過濾掉。

public class NextTest{  
    public static void main(String[] args) {  
        String s1,s2;  
        Scanner sc=new Scanner(System.in);  
        System.out.print("請輸入第一個字符串:");  
        s1=sc.next();  
        sc.nextLine();
        System.out.print("請輸入第二個字符串:");  
        s2=sc.nextLine();  
        System.out.println("輸入的字符串是:"+s1+" "+s2);  
    }  
}

  

請輸入第一個字符串:abc
請輸入第二個字符串:def
輸入的字符串是:abc def
View Code

 

參考來源:Java中Scanner用法總結


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM