我正在尝试为程序中的错误输入创建一些输入验证。
该程序应该将用户输入读取为double,但如果用户键入字母而不是数字,则必须显示输入不是数字的消息。
为此,我使用带有if语句的input.hasNextDouble。 else,打印x不是数字的消息。但是,我的问题在于用户输入的第二个数字。假设用户输入“5 f”hasNextDouble解释double,然后执行if语句下的代码,但由于“f”,输入仍然不正确。
简而言之,我需要一种方法让第一个输入(5)从缓冲区中删除,这样就可以解释第二个输入。
任何帮助表示赞赏!
这是一些示例代码:
if ( keyboard.hasNextDouble() ) {
double i = keyboard.nextDouble();
double j = keyboard.nextDouble();
double answer = (j+i );
System.out.println(answer);
}
else {
String a = keyboard.next();
String b = keyboard.next();
System.out.println( a + "is not a number");
答案 0 :(得分:1)
double i,j, answer;
try{
i = keyboard.nextDouble();
j = keyboard.nextDouble();
answer = i+j;
} catch( InputMismatchException e ) {
// One of the inputs was not a double
System.out.println("Incorrect format");
}
否则如果你绝对需要打印出不正确的内容,我会做if-then然后你有两次。
double i=null, j=null, answer;
// get input for i
if ( keyboard.hasNextDouble() ) {
i = keyboard.nextDouble();
}else{
System.out.println( keyboard.next() + " is not a double");
}
// get input for j
if ( keyboard.hasNextDouble() ) {
j = keyboard.nextDouble();
}else{
System.out.println( keyboard.next() + " is not a double");
}
// if both i and j received inputs
if( i != null && j != null )
answer = i + j;
else
System.out.println("Malformed input");
答案 1 :(得分:0)
你需要像以下一样。
double tryReadDouble(Scanner keyboard) throws NumberFormatException {
if (keyboard.hasNextDouble()) {
return keyboard.nextDouble();
} else {
throw new NumberFormatException(keyboard.next());
}
}
和
try {
double i = tryReadDouble(keyboard);
double j = tryReadDouble(keyboard);
double answer = (j + i);
System.out.println(answer);
} catch (NumberFormatException ex) {
System.out.println(ex.getMessage() + "is not a number");
}
希望这有帮助。
答案 2 :(得分:0)
您可以创建帮助方法,该方法将询问用户有效输入,直到获得有效输入,或者直到超过某些尝试限制。这种方法可能如下所示:
public static double getDouble(Scanner sc, int maxTries) {
int counter = maxTries;
while (counter-- > 0) {// you can also use `while(true)` if you
// don't want to limit numbers of tries
System.out.print("Please write number: ");
if (sc.hasNextDouble()) {
return sc.nextDouble();
} else {
String value = sc.next(); //consume invalid number
System.out.printf(
"%s is not a valid number (you have %d tries left).%n",
value, counter);
}
}
throw new NumberFormatException("Used didn't provide valid float in "
+ maxTries + " turns.");
}
然后您可以使用此方法,如
Scanner keyboard = new Scanner(System.in);
double i = getDouble(keyboard, 3);
double j = getDouble(keyboard, 3);
double answer = (j + i);
System.out.println(answer);