-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;
}
}
您的主代碼將在嘗試塊中執行您的邏輯,並且如果某些邏輯如何失敗,那麼它會在抓取博客處理它。 – Uzair