2015-04-15 127 views
1

所以我正在使用try/catch塊來捕獲(這是作業)的猜數遊戲。如果用戶輸入非整數值或低於或高於給定範圍的數字(在本例中爲1-10)。實現try/catch塊

但我有理解/正確放置try catch塊,我讀了它是如何工作的,但是當我嘗試將它實現到我的簡單代碼中時,它似乎被忽略。

下面是代碼

//import statements 
import java.util.*;  //for scanner class 


// class beginning 
class Guess { 
    public static void main(String[] args) { 
     //Declare variables area 

     int secretNumber, guess; 

     secretNumber = (int) (Math.random() * 10 + 1);   

     Scanner keyboard = new Scanner(System.in); 


     // beginning message to user to explain the program 
     System.out.println("Welcome to my guess a number program!"); 
     System.out.println("Please enter in a number to begin guess what the secret number is(1-10): "); 

     //Collect inputs from user or read in data here 

     System.out.println("Enter a guess (1-10): "); 
     try { 
      guess = keyboard.nextInt(); 
      if (guess < 1 || guess > 10){ 
      } 
     } catch (InputMismatchException e) { 
      guess= keyboard.nextInt(); 
      System.out.println("Not a valid integer"); 
     } 
     //Echo input values back to user here 



     //main code and calculations to do 
     do { 

      if (guess < 1 || guess > 10) { 
       System.out.println("Your guess is not in the corre try again."); 
       guess = keyboard.nextInt(); 
      } 
      if (guess == secretNumber) { 
       System.out.println("Your guess is correct. Congratulations!"); 
       guess = keyboard.nextInt(); 
      } else if (guess < secretNumber) { 
       System.out 
         .println("Your guess is smaller than the secret number."); 
       guess = keyboard.nextInt(); 
      } else if (guess > secretNumber) { 
       System.out 
         .println("Your guess is greater than the secret number."); 
       guess = keyboard.nextInt(); 
      } 
     } while (guess != secretNumber); 


     //End program message 
     System.out.println(); 
     System.out.println("Hope you enjoyed using this program!"); 
    }// end main method 


}// end class 

它不顯示"Your guess is correct. Congratulations!"當你猜對數。

我正在實現try catch塊嗎?如果不是,我怎麼能解釋它,所以我可以做第二個捕獲浮點數,字符串和任何不是int的東西。

它所做

  • 它正確地從1-10
  • 隨機化程序沒有檢查,看它是否在給定範圍

編輯下面 是內更新的代碼我現在唯一的問題是,我無法弄清楚如何應用另一個捕獲,如果用戶只需輸入沒有輸入任何內容我假設我需要從用戶的輸入變成一串然後比較?

//import statements 
import java.util.*;  //for scanner class 


// class beginning 
public class Guess { 
public static void main(String[] args) { 
    //Declare variables area 
    int guess, secretNumber = (int) (Math.random() * 10 + 1), lowGuess,highGuess; 
    Scanner keyboard = new Scanner(System.in); 

    // beginning message to user to explain the program 
    System.out.println("Welcome to my guessing number program!"); 
    System.out.println("Please enter in a number to start guessing(enter in a number between 1-10): "); 

    //main code and calculations to do 
    guess = 0; 
    lowGuess = 0; 
    highGuess = 11; 
    do { 
     try { 
      guess = keyboard.nextInt(); 
      if (guess < 1 || guess >10){ 
       System.out.println("Your guess is not in the correct range try again."); 
      } 
      else if(guess == secretNumber){ 
       System.out.println("Your guess is correct. Congratulations!"); 
      } 
      else if(guess < secretNumber && guess <= lowGuess){ 
       System.out.println("The number you entered is either the same entered or lower please re-enter"); 
      } 
      else if (guess < secretNumber && guess > lowGuess){ 
       lowGuess = guess; 
       System.out.println("Your guess is smaller than the secret number."); 
      } 
      else if (guess > secretNumber && guess >= highGuess){ 
       System.out.println("The number you entered is either the same entered or higher please re-enter"); 
      } 
      else if (guess > secretNumber && guess < highGuess){ 
       highGuess = guess; 
       System.out.println("Your guess is greater than the secret number."); 
      } 
     } catch (InputMismatchException e) { 
      System.out.println("Not a valid input please re-enter"); 
      keyboard.next(); 
      guess = 0; 
     } 
    } while (guess != secretNumber); 

    //End program message 
    System.out.println(); 
    System.out.println("Hope you enjoyed using this program!"); 
}// end main method 


}// end class 
+0

你只會第一次捕捉到異常,並且會丟失所有其他'nextInt()'。我建議你在do/while裏只做一次nextInt()。 – m0skit0

+2

您的縮進不會讓您的代碼更容易閱讀。也許讓你的IDE爲你的代碼格式化(在Eclipse中你可以使用'Source'菜單以及'Format'或'Correct Indentation')。 – Pshemo

+0

你告訴我們它不*做什麼。它會做什麼? –

回答

0

你想在這裏做什麼?

if (guess < 1 || guess > 10) { 
} 

你應該嘗試這樣的事:

public class Guess { 
    static int guess, secretNumber = (int) (Math.random() * 10 + 1); 
    static Scanner keyboard = new Scanner(System.in); 

    public static void main(String[] args) { 
     do { 
      try {  
       guess = keyboard.nextInt(); 
       if (guess < 1 || guess >10){ 
        System.out.println("Your guess is not in the corre try again."); 
       } 
       if(guess == secretNumber){ 
        System.out.println("Your guess is correct. Congratulations!"); 
       } 
       else if (guess < secretNumber){ 
        System.out.println("Your guess is smaller than the secret number."); 
       } 
       else if (guess > secretNumber){ 
        System.out.println("Your guess is greater than the secret number.");          
       } 
      } catch (InputMismatchException e) { 
       System.out.println("Not a valid integer"); 
      } 
     } while (guess != secretNumber); 
    } 
} 

編輯:你必須把一段代碼,這也許可以拋出一個異常,在try塊的範圍。知道將哪部分代碼放在try塊中是最先進的(不是太多也不是太少)。

在中間的嘗試,趕上你有你的主代碼/計算, 做什麼,然後你關閉其關閉,並結束與捕捉,看看是否 所有,如果輸入的內容是有效的後?

您可以隨時在頂層捕捉異常,就像您在這裏所說的那樣,但在實踐中,這不是實現它的方式。因爲當發生異常並且不捕獲它時,將會有一個名爲堆棧展開的進程。

理解堆棧展開如何工作以理解發生的事情非常重要。

你可以在這裏找到關於這個過程如何工作的信息:Explanation of stack unwinding。它解釋了C++中的堆棧展開,但我期望它在Java中(完全)相同。

+0

原始類型沒有equals方法 – Sanj

+0

只需在while內部移動try-catch,就不需要遞歸調用。 – m0skit0

+0

如果我知道這是如何工作的,你需要從try塊和你正在評估的代碼開始,在這種情況下它的if(guess <1 || guess> 10)'和輸出的消息一起在try和抓住你的主要代碼/計算工具,然後關閉它並結束捕獲,以查看是否畢竟如果輸入的內容是有效的? –

0

這是另一種方法,但使用例外。請閱讀this page瞭解try/catch塊如何工作。

//import statements 
import java.util.*;  //for scanner class 


// class beginning 
class Guess { 
public static void main(String[] args) { 
//Declare variables area 
int secretNumber, guess; 

secretNumber = (int) (Math.random() * 10 + 1); 

Scanner keyboard = new Scanner(System.in); 


// beginning message to user to explain the program 
System.out.println("Welcome to my guess a number program!"); 
System.out.println("Please enter in a number to begin guess what the secret number is(1-10): "); 

//Collect inputs from user or read in data here 


//main code and calculations to do 
do { 


    System.out.println("Enter a guess (1-10): "); 
    try { 
    guess = keyboard.nextInt(); 
    if (guess < 1 || guess > 10){ 
     throw new Exception("Number must be between 1 and 10"); 
    }else if(guess == secretNumber){ 
    throw new Exception("YOU WIN"); 
    } 
    else if (guess < secretNumber){ 
    throw new Exception("NUMBER IS +"); 
    } 
    else if (guess > secretNumber){ 
    throw new Exception("NUMBER IS -"); 
    } 
} catch (InputMismatchException e) 
{ 
    System.println("mustbeanumber"); 
} 
catch(Exception e) 
{ 
System.out.println(e.getMessage()); 
} 

} while (guess != secretNumber); 


//End program message 
System.out.println(); 
System.out.println("Hope you enjoyed using this program!"); 
}// end main method 


}// end class` 
+0

'IT's'?那是什麼? –

+0

這不是一個很好的解決方案AFAICT。它只會再試一次。 –

+0

我糾正了...... –