Throwing Exception
I am trying unsuccessfully to throw an exception TooLongEx if a user input fails. Been stuck on this forever :(
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();
}
}
}
}
Seems to work fine for me.
For
class TooLongEx extends Exception {}
I get (for an input length > 20)
Exception in thread "main" TooLongEx at MessageTooLong.main(MessageTooLong.java:26)
精彩评论