Exception 在我的游戏中哪里可以使用try/catch块?
这是我创造的游戏,我只需要在游戏中添加一个试抓,但我被卡住了Exception 在我的游戏中哪里可以使用try/catch块?,exception,methods,try-catch,Exception,Methods,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.
/**
*
* @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(){
这是另一个我认为可以通过尝试和捕捉来检查算术的领域
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;
}
}
由于异常主要用于处理错误或其他异常/意外事件,因此您的
answer()。想象一下,有什么事情会出你意想不到的差错
例如,当shake()
方法返回的值不能由switch
语句处理时,会发生什么情况?考虑一种情况,其中增加了随机数生成器的范围,并且忘记添加额外的情况;或者,您没有从配置文件动态加载足够的答案
一个简单的解决方案可能是添加一个默认值:
案例,返回一些“一概而论”的答案(例如,“我不知道”)。但是,更好的解决方案是让默认值:
案例抛出一个异常
,以指示您的方法对于某些卷没有答案
int roll = shake();
switch ( roll ) {
...
default:
throw new Exception( "No answer for roll: " + roll );
}
您的主代码进入try块,在那里您实现了您的逻辑,如果一些how逻辑失败了,那么它进入catch blog,在那里您处理它。