我有两个问题。首先,我在代码的第一部分创建了一个异常处理,即重试概念。
do {
try {
if(exitType.length()==1){
char exitChar = exitType.charAt(0);
exit = exitChar;
if (exit == 'Y' || exit == 'y' || exit == 'N' || exit == 'n') {
x = 1;
} else {
throw new StringException("Invalid letter...\n");
}
} else {
throw new StringException("Invalid input a string...\n");
}
} catch(StringException i) {
System.out.println("-------------------------------------------");
System.out.print("You typed: " + exitType + i);
System.out.println("-------------------------------------------");
System.out.println("Try again? (y/n): ");
exitType = input.next();
x = 0;
}
当用户输入除 y/n 之外的字母时,输出将是:
Try again? (y/n): w
-------------------------------------------
You typed: wStringException: Invalid letter...
-------------------------------------------
第一个问题:如何将 StringException: Invalid letter... 放在下一行,使其不在“w”旁边(只是为了输出的清晰和整洁)。希望你能得到我。
顺便说一句,我创建了自己的异常:
public class StringException extends Exception {
public StringException(String message) {
super(message);
}
}
其次,我不知道如何在要求用户输入选择字母的这部分添加异常处理:
public static void operation() {
Scanner input = new Scanner(System.in);
String choiceString = "";
char choice = 'a';
System.out.print("Enter letter of choice: ");
choiceString = input.next();
if (choiceString.length() == 1) {
choice = choiceString.charAt(0);
System.out.println("-------------------------------------------");
switch(choice) {
case 'a': {
try {
System.out.print("Enter width: ");
double width = input.nextDouble();
System.out.print("Enter height: ");
double height = input.nextDouble();
System.out.print("What is the color of the shape? ");
String color = input.next();
System.out.println("-------------------------------------------");
Shape cia;
Shape rec = new Rectangle(color, width, height);
cia = rec;
System.out.println(rec);
Rectangle r = new Rectangle(color, width, height);
r.print();
} catch(InputMismatchException i) {
System.out.println("InputMismatchException caught");
}
break;
}
case 'b': {
//****
}
case 'c': {
//****
}
default:
System.out.println("Invalid choice...");
}
} else {
System.out.println("Invalid input...");
}
我只需要知道应该将 try-catch 块放置在提示选择字母的部分的位置。