2014-09-03 172 views
3

問題的單線讀整數和字符串是這樣的:從控制檯

我有兩個節目,其需要從控制檯輸入,但在不同的方式: 1)

Scanner input = new Scanner(System.in); 
    int temp1 = input.nextInt(); 
    input.nextLine(); 
    String str = input.nextLine(); 
    int temp2 = Integer.parseInt(str); 
    int total = temp1+temp2; 

    System.out.println(total); 

2)

Scanner input = new Scanner(System.in); 
    int temp1 = input.nextInt(); 
// input.nextLine(); 
    String str = input.nextLine(); 
    int temp2 = Integer.parseInt(str); 
    int total = temp1+temp2; 

    System.out.println(total); 

在第一殼體1取輸入在2個不同的線等

1 
2 

所以它給出正確答案,但是在第二情況下,我除去input.nextLine()語句採取輸入在像一個單一的線:

1 2 

它給我數字格式異常爲什麼?並建議我如何從控制檯的一行讀取整數和字符串。

回答

1

問題是str的值爲" 2",並且前導空格不是parseInt()的合法語法。您需要跳過輸入中兩個數字之間的空格,或在解析之前修剪str之外的空格。要跳過空格,這樣做:

input.skip("\\s*"); 
String str = input.nextLine(); 

要調節空間過的str解析之前,這樣做:

int temp2 = Integer.parseInt(str.trim()); 

您也可以看中,並在一個讀取該行的兩件去:

if (input.findInLine("(\\d+)\\s+(\\d+)") == null) { 
    // expected pattern was not found 
    System.out.println("Incorrect input!"); 
} else { 
    // expected pattern was found - retrieve and parse the pieces 
    MatchResult result = input.match(); 
    int temp1 = Integer.parseInt(result.group(1)); 
    int temp2 = Integer.parseInt(result.group(2)); 
    int total = temp1+temp2; 

    System.out.println(total); 
} 
+0

是的,它的工作表示感謝。 – Spartan 2014-09-03 14:41:46

1

假設輸入是1 2,這條線

String str = input.nextLine(); 

str等於" 2"之後,因此它不能被解析爲INT。

你可以簡單地做:

int temp1 = input.nextInt(); 
int temp2 = input.nextInt(); 
int total = temp1+temp2; 
System.out.println(total); 
+0

是的,但是這個問題的解決方案是什麼? – Spartan 2014-09-03 14:31:49

+0

@pushpendra我提供瞭解決問題的代碼。 – 2014-09-03 14:32:31

+0

解決方案是input.skip(「\\ s *」);因爲在我們需要真正的字符串如「abc」的情況下,那麼您的解決方案是不夠的。 – Spartan 2014-09-03 15:07:03

0

在你的下一行有沒有整...它試圖創建和空整數...所以你會得到數甲例外。如果在temp1上使用分割字符串,則會得到2個值爲1和2的字符串。