【问题标题】:Where can i use a try/catch block in my game?在我的游戏中哪里可以使用 try/catch 块?
【发布时间】:2017-01-20 21:06:58
【问题描述】:

这是我创建的游戏,我只需要以某种方式添加一个 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 and 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;
        }
}

【问题讨论】:

  • 你的主要代码进入你实现逻辑的 try 块,如果某些逻辑失败了,那么它进入你处理它的 catch 博客。

标签: exception methods try-catch


【解决方案1】:

由于异常主要用于处理错误或其他异常/意外事件,因此您的 answer() 方法是一个很好的候选者。想象一下您可能没有预料到的问题。

例如,当您的shake() 方法返回一个您的switch 语句无法处理的值时会发生什么?考虑一种情况,您增加了随机数生成器的范围而忘记添加其他案例;或者,您没有从配置文件中动态加载足够的答案。

一个简单的解决方案可能是添加一个default: 案例,该案例返回一些“包罗万象”的答案(例如“我不知道”)。但是,更好的解决方案是让 default: 案例抛出一个 Exception 以表明您的方法对于某些滚动没有答案。

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

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 2018-08-22
    • 2016-07-02
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-08
    相关资源
    最近更新 更多