2014-06-13 2 views
-2
import java.util.Scanner; 

public class test { 

/** 
* @param args 
*/ 
public static void main(String[] args) 
{ 
    Scanner input = new Scanner (System.in); 
    boolean US1 = false; 
    boolean game; 
    int score = 1; 
    int wage = 0; 
    int fin_score = 0; 
    String ans; 

    if (US1 == false) { 
     game = false; 
     System.out.println (score); 
     System.out.println("Enter a wager"); 
     wage = input.nextInt(); 
    } 

    if (wage < score) { 
     System.out.println ("What is the capital of Liberia?"); 
     ans = input.next(); 

     if (ans.equalsIgnoreCase("Monrovia")) { 
      System.out.println ("You got it right!"); 
      System.out.println ("Final score " + fin_score); 
     } 
    } 
} 
} 

InputMismatchException을 사용하여 솔루션 {{catch} {}을 찾았지만 코드에 구현되면 작동하지 않습니다. 여기에 이것을 구현할 수있는 방법이 있습니까? 입력 한 임금이 정수가 될 때까지 반복하는 루프를 만들려고합니다.입력 한 숫자가 int인지 확인

+0

당연히 이러한 접근 방식 (try/catch 사용)이 작동합니다. 따라서 (도시되지 않은) 구현은 잘못되었을 것임에 틀림 없다. – user2864740

+0

당신은 무엇을 시도 했습니까? 이 경우 온라인으로 솔루션을 사용할 수 있습니다. – nook

답변

0

잘못된 입력을 확인하기 위해 코드에 여러 catch 예외를 사용할 수 있습니다. 예를

try{ 

    wage = input.nextInt(); 

catch (InputMismatchException e){ 
    System.out.print(e.getMessage()); 
    //handle mismatch input exception 
} 

catch (NumberFormatException e) { 
    System.out.print(e.getMessage()); 
    //handle NFE 
} 

catch (Exception e) { 
    System.out.print(e.getMessage()); 
    //last ditch case 
} 

를 들어 다음 중 어떤 스캐너 오류에 대해 잘 작동,하지만 InputMismatchException 사용이 최고입니다. try-catch 블록을 사용하여 작동하지 않는 코드를 포함하면 큰 도움이됩니다.

+1

질문에 대답하지 않습니다 ... "입력 한 임금이 정수가 될 때까지 반복하는 루프를 만들려고합니다." 또한 nextInt는 stdin에 좋지 않습니다. 전체 행이 유효하다는 것을 보지 않으며 행에 다른 단어/정수를 남겨 둡니다. – Runemoro

0

우선 Scanner.nextInt은 공백과 개행 문자를 구분 기호로 사용하기 때문에 Scanner.nextLine을 사용해야합니다. 이는 원하는 것이 아닐 수 있습니다 (공백이 스캐너에 남겨져 다음 읽기가 깨지는 경우).

이 대신보십시오 :

boolean valid = false; 
System.out.print("Enter a wager: "); //Looks nicer when the input is put right next to the label 
while(!valid) 
    try { 
     wage = Integer.valueOf(input.nextLine()); 
     valid = true; 
    } catch (NumberFormatException e) { 
     System.out.print("That's not a valid number! Enter a wager: "); 
    } 
} 
+0

정확히 어디에서 코드에 삽입합니까? 그것은 작동하지만 정수를 입력하면 충돌이 발생합니다. – user3734973

+0

@ user3734973 :'System.out.println ("Enter wager"); 및'wage = input.nextInt(); 또한, 프로그램이 java ** crash **를 만든다면, 다시 설치하는 것이 좋습니다. 방금 예외가 발생하면 예외를 붙여 넣으십시오! – Runemoro

0

예! 이 작업을 수행하는 좋은 방법이 있습니다.

Scanner input = new Scanner(System.in); 
    boolean gotAnInt = false; 
    while(!gotAnInt){ 
     System.out.println("Enter int: "); 
     if(input.hasNextInt()){ 
      int theInt = input.nextInt(); 
      gotAnInt = true; 
     }else{ 
      input.next(); 
     } 

    } 
관련 문제