2016-11-28 49 views
0
import java.util.Scanner; 
public class HelloWorld{ 
    public static void main(String args[]){ 
    Scanner dd = new Scanner(System.in); 
    System.out.println("Enter name"); 
    String b = dd.nextLine(); 
    System.out.println("Enter num"); 
    int num = dd.nextInt(); 
    } 
} 

而且兩個多用戶輸入程序有什麼區別?

import java.util.Scanner; 
public class HelloWorld{ 
    public static void main(String args[]){ 
     Scanner dd = new Scanner(System.in); 
     System.out.println("Enter num"); 
     int num = dd.nextInt(); 
     System.out.println("Enter name"); 
     String b = dd.nextLine(); 
    } 
} 

爲什麼後者不peoperly工作(並不讓我輸入其名稱),而第一個呢?

我編寫了一個新版本,沒有那個煩人的「掃描儀掃描=新的掃描儀」。 那麼這個解決方案呢?它可能有什麼缺點?

import java.util.Scanner; 
public class HelloWorld{ 
public static void main(String args[]){ 
    System.out.println("Enter num"); 
    int i = new Scanner(System.in).nextInt(); 
    System.out.println("Enter name"); 
    String b = new Scanner(System.in).nextLine(); 
    } 
} 
+0

也許你應該使用nextLine()古今中外值轉換成正確的類型 – cralfaro

回答

0

在第二種情況下,nextInt()不掃描過在按下返回鍵時用戶輸入的換行符。

在第一種情況下,首先遇到nextLine(),所以問題不會表現出來。

故事的寓意是總是使用nextLine()並相應地解析得到的字符串。使用像Integer#parseInt這樣的字符串轉換爲整數。

+0

它說:「字符串不能轉換成int」 –

+0

當然會的。看到我最後一個新的句子。 – Bathsheba

0

第二個程序需要一個Int,然後是一個名字。因此,輸入名稱時可能會出錯。