2017-01-20 39 views
-2

這是我創建的遊戲,我只是需要添加一個嘗試捕捉到它不知何故,我卡住了。我在哪裏可以在我的遊戲中使用try/catch塊?

/** 
* 
* @author 
*/ 
import java.util.*; 
public class magiceightball { 
public static void main (String [] args){ 
    questions(); 
} 
public static void questions(){ //method  

    Scanner input = new Scanner(System.in); 

     while(true){ 

     System.out.println(); 
     System.out.println("Welcome to the Magic 8 Ball Game!"); 
     System.out.println("Shake(Type 'Shake' to have you question answered, or type 'No more'to end the game"); 
     String request = input.nextLine(); 

我覺得這裏是我可以添加一個嘗試

 if (request.equalsIgnoreCase("shake")){ 
    answer(); 
    } 
     else if(request.equalsIgnoreCase("No more")){ 
     break; 
    } 
     else{ 
     System.out.println("Invalid answer. Please try again!"); 
    } 
} 

} 

    public static void answer(){ 

    switch(shake()){ 
     case 1:System.out.println("It is certain"); 
      break; 
     case 2:System.out.println("It is decidedly so"); 
      break; 
     case 3:System.out.println("Most likely"); 
      break; 
     case 4:System.out.println("Ask again later"); 
      break; 
     case 5:System.out.println(" Better not tell you now"); 
      break; 
     case 6:System.out.println("Don't count on it"); 
      break; 
     case 7:System.out.println("My reply is no"); 
      break; 
     case 8:System.out.println("My sources say no"); 
      break; 
     case 9:System.out.println("Unlikely"); 
      break; 
     case 10:System.out.println("Doubtful"); 
      break; 
    } 

} 
     public static int shake(){ 

這是另一個領域,我認爲可以使用try和catch來檢查算術

Random rand = new Random();//using random numbers 
     int randomInt = rand.nextInt(10 - 1 + 1) + 1;//i used this to get a random number from 1-10 
     System.out.println(randomInt); 
     return randomInt; 
     } 
} 
+0

您的主代碼將在嘗試塊中執行您的邏輯,並且如果某些邏輯如何失敗,那麼它會在抓取博客處理它。 – Uzair

回答

1

由於例外主要用於處理錯誤或其他特殊/意外事件,這種方法的一個好的候選者將是您的方法answer()。想象一下你可能預料不到的錯誤。

例如,如果shake()方法返回的值不能由您的switch語句處理,會發生什麼情況?考慮一種情況,你增加了你的隨機數發生器的範圍,忘記增加額外的情況;或者,您沒有從配置文件動態加載足夠的答案。

一個簡單的解決方案可能是添加返回一些「無所不包」的答案(例如,「我不知道」)一個default:情況。但是,更好的解決方案是讓default:案例拋出Exception來表明您的方法對某些卷沒有答案。

int roll = shake(); 
switch (roll) { 
    ... 
    default: 
     throw new Exception("No answer for roll: " + roll); 
} 
相關問題