2015-12-11 16 views
0
if (userOption == 2) { 
    System.out.println("You have chosen produce! Please enter (1) for organic or (0) for non-organic."); 
    type = sc.nextInt(); 
    System.out.println("Please enter a name for this produce."); 
    name = sc.next(); 
    sc.nextLine(); 
    System.out.println("Please enter the amount of calories."); 
    calories = sc.nextInt(); 
    System.out.println("Please enter the amount of carbohydrates."); 
    carbohydrates = sc.nextInt(); 

    list.add(new Produce(name, calories, carbohydrates, type)); 
} 

你好,當我把我的話之間的空間爲輸入「姓名」,它給了我一個錯誤InputMismatchError的熱量時,即時通訊中的熱量沒有推杆,在用戶輸入「姓名」之前,卡路里甚至不應該得到輸入。謝謝:)代碼一直給人一種InputMismatchException時當我輸入2個字

+3

你正在使用'sc.nextInt()'這是等待一個int,一個INTE ger不能包含空格,這是你的意思嗎? –

+0

它期待一個int,而不是單詞。 – Stultuske

+0

您預計卡路里是一個整數,而不是一個字符串 – TheLostMind

回答

0

看來你試圖輸入一個StringInteger。捕捉到了這個,你可以更改您的代碼是這樣的:

if (userOption == 2) { 
      System.out.println("You have chosen produce! Please enter (1) for organic or (0) for non-organic."); 
      try { 
       type = sc.nextInt(); 
      } catch (InputMismatchException e) { 
       System.out.println("Wrong format entered."); 
       // ask question again or move on. 
      } 
      System.out.println("Please enter a name for this produce."); 
      name = sc.next(); 
      sc.nextLine(); 
      System.out.println("Please enter the amount of calories."); 
      calories = sc.nextInt(); 
      System.out.println("Please enter the amount of carbohydrates."); 
      carbohydrates = sc.nextInt(); 

     list.add(new Produce(name, calories, carbohydrates, type)); 
    } 

的try/catch語句將捕獲該異常,並告訴他們有什麼做錯了用戶。

1

您的輸入是「牛肉炸玉米餅」,其中包含一個白色空間。所述Java-Doc狀態:

掃描器斷開其輸入到使用定界符圖案, 它默認與空白匹配。

因此,您的sc.next();返回「牛肉」,在流上留下「Taco」。你的下一個sc.nextInt();然後返回「塔科」,這是沒有整數並導致成InputMismatchException其中states

InputMismatchException - 如果下一個標記不匹配Integer正則表達式,或者超出範圍


要修復它試試這個:

System.out.println("You have chosen produce! Please enter (1) for organic or (0) for non-organic."); 
int type = sc.nextInt(); 
// Clear the input 
sc.nextLine(); 
System.out.println("Please enter a name for this produce."); 
// Read in the whole next line (so nothing is left that can cause an exception) 
String name = sc.nextLine(); 
+0

我將如何解決這個問題? – elequang

+0

@elequang檢查編輯 –

+0

@elequang這樣做可以幫助您? –

相關問題