【发布时间】:2014-10-12 13:43:44
【问题描述】:
正在建设书店系统 其中一种方法会要求用户输入书名,然后是描述,然后是书的代码。 我的问题是,如果有“InputMismatchException”,我怎么能回忆起尝试。 我的意思是捕获将打印到屏幕“错误输入!”但我想提示用户再次输入
这是我的代码
public void add(){
try{
System.out.println("Enter the book code :");
int c = s.nextInt();
try{
System.out.println("Eneter the book quantity");
int q = s.nextInt();
try{
System.out.println("Eneter the book description");
String d = s.next();
try{
System.out.println("Eneter the book cost price");
double cp = s.nextDouble();
try{
System.out.println("Eneter the book selling price");
double sp = s.nextDouble();
try{
System.out.println("Enter status: [a for available - u for unvailable]");
String input = s.next();
if(input.equals("a")) {
System.out.println("available: ");
}
else if (input.equals("u")) {
System.out.println("unavailable ");
}
else {
System.out.println("Wrong Input");
}
try{
System.out.println("enter the discount on the item \"if exsist\"");
double dis = s.nextDouble();
}catch(InputMismatchException e){
System.out.println("Wrong Input");
}
}catch(InputMismatchException e){
System.out.println("Wrong input");
}
}catch(InputMismatchException e){
}
}catch(InputMismatchException e){
System.out.println("WRONT INPUT!!");
}
}catch(InputMismatchException e){
System.out.println("WRONG INPUT!!");
}
} catch(InputMismatchException e){
System.out.println("Wrong input. NUMBERS only!!");
}
} catch(InputMismatchException e){
System.out.println("You have to enter a NUMBER only");
}
【问题讨论】:
-
为什么要这样嵌套?
-
你提示的每一个部分都应该是一个自己的方法。在方法内部,您处理循环,直到获得有效输入(或退出标志)。当方法返回时,它将返回有效输入(可能需要多次尝试)或标志(可能返回
null),表示结束此输入。 -
圣牛鳄梨
-
你的代码中不应该有那么多尝试!
-
@mazin 你需要一个循环。
try-catch不会循环。如果您想多次重复某些内容(这就是您正在做的事情,因为您要求用户多次输入直到他正确为止),这就是循环的用途,那么您为什么不想使用 a循环?
标签: java