2017-12-01 7 views
0

이번이 처음입니다. 나는 코드 작성법을 배우기 시작 했으므로 나는이 질문이 내가 여기에서 찾을 수있는 것이 아니라고 솔직하게 희망한다! (나는 잠시 동안 수색을하겠다고 약속하지만, 나는이 주제의 멍청이이기 때문에 나의 의심을 해결하기 위해 나를 이해할 수있는 것을 찾지 못했다.)자바 이해가 안됨 시도 캐치

Java에서 간단한 게임을하고 있는데, 프로그램에서 임의의 숫자를 생성하고 플레이어가 생성 된 숫자를 추측해야합니다. 플레이어가 숫자를 입력하면 게임은 무작위로 생성 된 숫자보다 높거나 낮 으면 힌트를 표시합니다.

숫자 만 입력하면 프로그램 자체가 제대로 작동하지만 잘못된 사용자 입력을 처리하기 위해 try-catch 문을 추가하려고합니다.

나는 내 코드에서 보여준대로 문장을 사용했지만, 왜 다른 숫자를 입력 할 때 예외가 발생하여 시스템 콘솔에 출력되기 때문에 왜 제대로 작동하지 않는지 이해할 수 없다. out.println(),이 때 프로그램이 종료됩니다.

예외가 catch 될 때마다 프로그램을 종료하지 않고 번호를 입력하는 것만을 시도하려고합니다. 어떻게 해결할 수 있습니까?

도움을 주셔서 감사합니다.

import java.util.Scanner; 

public class HiLo { 

    public static void main(String[] args) { 
     Scanner scan = new Scanner(System.in); //Creates Scanner object to read from keyboard 
     String playAgain = ""; //if == y, game restarts 
     try { 
      do { 
       // Create a random number for the user to guess 
       int theNumber = (int)(Math.random() * 100 + 1); 
       //System.out.println(theNumber);  //Uncoment this in case we want to know the number (for testing). 
       int guess = 0; //Number entered by the player 
       int count = 0; //Number of tries of guessing the number 
       while(guess != theNumber){ 
        System.out.println("Guess a number between 1 and 100:"); 
        guess = scan.nextInt(); //Reads the number typed on the keyboard by the player 
        count++; //Plus 1 every time a number is entered 
        System.out.println("You entered " + guess +"."); 
        if(guess < theNumber) { //If number entered is smaller 
         System.out.println("The number is bigger" + ", try again!"); 
         System.out.println("Number of tries: " + count); 
        } else if(guess > theNumber) { //If number entered is bigger 
         System.out.println("The number is smaller" + ", try again!"); 
         System.out.println("Number of tries: " + count); 
        } else { //If both previous cases are false 
         System.out.println("Congratulations! You've found the number!"); 
        } 
       } 
       //Once guess == theNumber 
       System.out.println("Number of tries: " + count); 
       System.out.println("Play again? (y/n)"); 
       playAgain = scan.next(); //Reads the String entered from keyboard by the player 
      } 
      while(playAgain.equalsIgnoreCase("y"));  //If player enters y, start again. 
      //Otherwise 
      System.out.println("Thank you for playing! Goodbye :)"); 
     } catch (Exception e) { 
      System.out.println("Incorrect entering! Please enter a number between 1 and 100."); 
     } 
     scan.close(); //Close scanner 
    } //Close main 
} //Close class 
+1

프로그램 때문에 스캐너를 폐쇄하고있어 catch' 당신'에서 복귀 한 후 종료 main, 그래서 당신은 무엇을 기대 했습니까? – tkausl

+0

그러면 어떻게 해결할 수 있습니까? do-while 문 구조를 수정하면 Eclipse에서 오류가 발생하고 컴파일을 허용하지 않습니다. "System.out.println()"다음에 "guess = scan.nextInt()"를 추가하려고 생각했지만 작동하지 않습니다. – Vicentequesada

답변

1

장소 while 루프 내부-캐치를 시도하고 스캐너 객체를 reinstantiate (catch 블록 내부에 = 새로운 스캐너 (System.in)를 검사합니다.

while (guess != theNumber) { 
        try {      
         System.out.println("Guess a number between 1 and 100:"); 
         guess = scan.nextInt(); // Reads the number typed on the 
         // keyboard by the player 
         count++; // Plus 1 every time a number is entered 
         System.out.println("You entered " + guess + "."); 
         if (guess < theNumber) { // If number entered is smaller 
          System.out.println("The number is bigger" + ", try again!"); 
          System.out.println("Number of tries: " + count); 
         } else if (guess > theNumber) { // If number entered is 
          // bigger 
          System.out.println("The number is smaller" + ", try again!"); 
          System.out.println("Number of tries: " + count); 
         } else { // If both previous cases are false 
          System.out.println("Congratulations! You've found the number!"); 
         } 
        } catch (Exception e) { 
         System.out.println("Incorrect entering! Please enter a number between 1 and 100."); 
         scan = new Scanner(System.in); 
        } 
       } 
+0

좋아요! 매력처럼 작동합니다! 정말 고맙습니다! 저는 여전히 한 가지 질문이 있습니다. 다른 스캐너 개체를 만들어야하는 이유는 무엇입니까? 나는 이해하지 못한다. 내가 배울 수 있도록 나에게 설명해 줄 수 있니? 시간 내 주셔서 감사합니다. – Vicentequesada

+0

한 번 더 의견을 말하면, 완벽하게 작동하려면 스캐너 객체가 한 개 더 필요했지만 왜 하하하인지는 잘 모르겠습니다. 당신이 그것을 설명 할 수 있다면 그것은 굉장 할 것입니다! : D 고마워! – Vicentequesada

+0

scan.nextInt()가 먼저 실행 된 다음 입력 변수를 추측 변수에만 할당합니다. int가 아닌 입력은 scan.nextInt()에서 예외를 throw합니다. 반복하는 동안 scan.nextInt()는 비 int 입력을 보유하므로 예외를 계속 throw합니다. 무한 루프가 발생합니다. 이 문제를 해결하려면 스캐너 개체가 비 int 입력 값을 보유하고 있지 않은지 확인해야합니다. 이를 수행하는 한 가지 방법은 catch 블록에 새 Scanner 객체를 만드는 것입니다. – Barr3l3y3

-1

을 당신은의 작업을 이해하는 데 필요한 try-catch 블록을 사용할 수 있습니다. try 내에서 전체 코드를 둘러 쌀 필요가 없습니다. 예외가 발생하는 코드의 일부만 입력하면됩니다. 따라서 귀하의 경우에는 guess = scan.nextInt();을 둘러싼 다음 예외를 잡으십시오. 문이 정수가 아닌 경우 예외가 발생하므로 사용자 입력이의 각 반복에 대해 유효하다는 것을 확인할 수 있습니다.루프.

Edit_1 : 나는 당신의 코드에서 try-catch 블록을 제거하고 나를 위해 잘 작동 다음 & 추가 :

try{ 
    guess = scan.nextInt();} //Reads the number typed on the keyboard by the player 
catch (InputMismatchException e){ 
    System.out.println("Incorrect entering! Please enter a number between 1 and 100."); 
    scan.nextLine(); 
    continue; 
} 
+0

그래, 그게 해결책이 될 수 있다고 생각했는데, 단어를 입력하면 while 조건이 항상 거짓이기 때문에 프로그램을 마쳤다. (예 :)/ – Vicentequesada

+0

'scan.nextLine()'을 이것을 사용할 수있는'catch' 블록. 나는 내 뜻을 보여주기 위해 나의 대답을 편집했다. –

+0

왜 계속 진술을 사용합니까? – Vicentequesada