创建和调用自定义例外

时间:2017-03-13 15:26:25

标签: java exception

我正在编写一个生成随机数的HighLow游戏,然后要求用户猜测它是什么。然后输入将得到“太高”的响应," "太低了,"或"正确。"我把游戏做得很好,但问题是:太高了," "太低了,"并且"纠正"响应必须使用自定义异常类。我已经创建了自定义异常类,但我不知道如何让程序去除异常(任何帮助都非常适合)。我尝试用以下代码替换原始代码,但它甚至没有接近工作:

if (guess < number) { 
throw TooLowException;   
} else if (guess > number) {
throw TooHighException;    
} else {
throw CorrectException;
}

原始代码:

import java.util.Random;
import java.util.Scanner;


public class HelloWorld {

    public class TooHighException extends Exception {
    }

    public class TooLowException extends Exception {
    }

    public class CorrectException extends Exception {
    }

    public static void main(String[] args) {
        Random random = new Random();
        Scanner scanner = new Scanner(System.in);
        int number = random.nextInt(100);
        int guess = -1;
        while (guess != number) {
            System.out.print("Enter your guess: ");
            guess = scanner.nextInt();
            if (guess < number) {
                System.out.println("Too low, guess again");
            }
            else if (guess > number) {
                System.out.println("Too high, guess again");
            }
            else {
                System.out.println("Correct, the random number was " + number);
            }
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您可以使用以下代码让您的想法发挥作用:

<route>
   <from uri="imap://admin@mymailserver_1"/>
   <to uri="direct:processMail"/>
</route>

<route>
   <from uri="imap://admin@mymailserver_2"/>
   <to uri="direct:processMail"/>
</route>

<route>
   <from uri="direct:processMail"/>
   <to uri="bean:MailService?method=process"/>
   <to uri="activemq:queue:mail.out"/>
</route>    

}

答案 1 :(得分:0)

异常是类,你必须创建它们的实例,如下所示:

if (guess < number) { 
    throw new TooLowException();   
} else if (guess > number) {
    throw new TooHighException();
} else {
    throw new CorrectException();
}

答案 2 :(得分:0)

不要使用例外来控制流量。这是一个猜谜游戏,三种可能性中没有一个是例外,在考虑了这个类名后,这一点变得非常清楚:CorrectException