2017-09-14 1 views
-1

여기에 NumberFormatException이 표시되는 이유는 무엇입니까? 내가 대신 내가 대신 문자열의 int 형의 코드를 촬영했다 이전 Integer.parseInt() .Also, 나는이 예외Integer.parseInt()를 사용하여 NumberFormatException 받기

앞에서 내가 스캐너 클래스의 nextInt() 방법을 사용했기 때문에 InputMismatchException을 사용있어 이유를 이해 할 수없는 1로 코드 값을 입력 그러나 지금 그것을 변경했다.

나는 이것이 sc.nextLine()과 관련이 있다고 생각하지만, 런타임시 사용자 입력을 건너 뛰지는 않습니다.

public void searchItem() { 

    String code = ""; 
    NewItem foundItem; 
    String searchdisString = ""; 
    int finalCode = 0; 

    if (ItemList != null && ItemList.size() > 0) { 
     System.out.println("Enter Item code:"); 
     try { 
      code = sc.nextLine(); 
      sc.nextLine(); 

      // Line 142 below 
      finalCode = Integer.parseInt(code); 
     } catch (InputMismatchException e) { 
      System.out.println("Please enter a valid code."); 
      return; 
     } 
     foundItem = search(code); 
     if (foundItem == null) { 
      System.out.println("Item not found"); 
      return; 
     } 

     else { 
      System.out.println(foundItem.toString()); 
     } 
    } else { 
     System.out.println("No items to search. Please go to #3 to add items first.\nThank you."); 
    } 
} 

출력 :

New Shop for Items created. 
-----ITEM------ 
1. Display all items 
2. Search items 
3. Add items to list 
4. Add items to cart 
5. Display cart 
6. Issue item 
7. Exit 
Choice: 
3 
Enter Item code: 
1 
Item name : 
apple 
apple 
Rate : 
20 
Quantity : 
30 
1. Display all items 
2. Search items 
3. Add items to list 
4. Add items to cart 
5. Display cart 
6. Issue item 
7. Exit 
Choice: 
2 
Enter Item code: 
1 

오류 :

Exception in thread "main" java.lang.NumberFormatException: For input string: "" at
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:504) at java.lang.Integer.parseInt(Integer.java:527) at NewShop.searchItem(NewShop.java:142) at NewShoppingCart.main(NewShoppingCart.java:45)

편집 :

if(ItemList!=null&&ItemList.size()>0) 
     { 
     System.out.println("Enter Item code:"); 
     try{ 
      code = sc.nextLine(); 

      finalCode = Integer.parseInt(code.trim()); 
      } 
     catch(InputMismatchException e){ 
     System.out.println("Please enter a valid code."); 
     return; 
     } 

출력 :

012,346,230,239,362,414,
+0

지금 던지지 말 것! 어쩌면 다른 메소드에서 사용 된 sc.nextLine() 함수와 관련이있을 수도 있습니다. –

답변

3
code = sc.nextLine(); 
sc.nextLine(); // reading extra line 

// Line 142 below 
finalCode = Integer.parseInt(code); 

추가 행이 비어 있습니다. 그냥 제거하고 작동합니다.

sc.nextLine(); // reading extra line 
code = sc.nextLine(); 
// Line 142 below 
finalCode = Integer.parseInt(code); 
+0

작동하지 않습니다. 코드에 대한 사용자 입력을 건너 뛴 다음 다시 예외를 던졌습니다. –

+0

@SHACHINDRATRIPATHI emtpy 줄을 맨 위에 놓을 수 있습니까? –

+0

편집을 참조하십시오 –

0

일부 공백이있을 수 있습니다.

시도 : finalCode = Integer.parseInt(code.trim());

+0

불행히도 :( –

+0

EDIT –

+0

빈 문자열을 구문 분석 할 수 있는지 확인하십시오, 그 전에 예외가 될 수 있습니다 –