0

如果用户输入失败,我尝试抛出异常 TooLongEx 失败。永远被困在这上面:(

import java.util.Scanner;
public class MessageTooLong extends Exception {
    public static void main(String args[])
    throws TooLongEx {
        Scanner keyboard = new Scanner(System.in);
        String line;
        char preference;
        int length;
        boolean go = true;
        while (go) {
            System.out.println("Enter a line of text.");
            System.out.println("Use no more than 20 characters.");
            line = keyboard.next();
            length = line.length();
            if (length <= 20) {
                    System.out.println("You entered " + length + " characters, which is an acceptable length.");
                    System.out.println("Would you like to enter another line?");
                    System.out.println("Enter 'y' to continue or 'n' to quit.");
                    preference = keyboard.next().charAt(0);
                if ((preference == 'y') || (preference == 'Y')) {
                    go = true;
                } else {
                    go = false;
                }
            } else {
                throw new TooLongEx();
            }
        }
    }
}
4

1 回答 1

2

似乎对我来说工作得很好。

为了

class TooLongEx extends Exception {}

我得到(对于输入长度> 20)

MessageTooLong.main(MessageTooLong.java:26) 处的线程“主”TooLongEx 中的异常

于 2011-05-01T04:44:23.313 回答