嗨在我的程序中,如果我在字段中输入数字,它应显示为有效值,如果我输入字母或特殊字符,它应显示为无效值,但是当我运行以下代码时,如果我输入单词则显示错误作为输入,如果输入数字,则表示格式正确
package quantity;
import java.util.Scanner;
public class Quantity {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
System.out.println("enter input");
double qty = input.nextDouble();
System.out.println(" input ="+qty);
if(!("[_a-z_A-Z_)+").equals("qty")||
!("[_!_~_@_#_$]").equals("qty"))
{
System.out.println("correct format");
}
// TODO code application logic here
else
{
System.out.println("wrong input");
}
}
}
显示以下错误
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at quantity.Quantity.main(Quantity.java:19)
答案 0 :(得分:0)
或... 你可以像这样自己捕捉异常:
import java.util.Scanner;
public class Answer {
private static final Scanner IN = new Scanner(System.in);
public static void main(String[] args) {
double qty;
while(true){ //infinite loop
try{
System.out.println("Please enter the qty:");
qty = IN.nextDouble();
System.out.println("You entered " + qty);
//do something with qty
}catch(Exception e){
System.out.println("Please input the number in double format");
IN.next(); //consume the wrong input
}
}
}
}