如何检查用户输入的是双精度类型?



我试图让用户以数字格式给我一个直径,如果他们输入字符串,程序不会崩溃。这段代码告诉我输入是否是整数,但它只有在你输入两次答案后才有效。如何让它告诉我第一个用户输入是否是整数?

import java.util.*;
import java.util.InputMismatchException;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while(true) {
System.out.print("What is the diameter: ");
try {
double diameter = input.nextDouble();
break;
}catch (InputMismatchException e) {
System.out.println("Please enter a number: ");
}
}
input.close();
}
}

为什么不直接提示以double类型开始呢?对于像对象的维度这样的东西,接受所有double是合适的。如果您希望提示字符串,请使用input.next()进行输入。你仍然可以捕获异常。

double diameter;
while (true) {
System.out.print(
"What is the diameter of the sphere (cm): ");
try {
diameter = input.nextDouble();
break;  // get out of the loop
} catch (InputMismatchException mme) {
System.out.println("double value not entered");
// clear the scanner input
input.nextLine();
}
}
System.out.println("The diameter is " + diameter);

假设您想要查看项目是否是双精度(而不是整数),一种方法是使用nextDouble()读取输入作为双精度,并捕获InputMismatchException,以防它不是。使用while循环,可以反复要求用户输入一个值,直到输入一个有效的双精度类型。

Double diameter = null;
while (diameter == null) {
try {
diameter = input.nextDouble();
} catch (InputMismatchException e) {
System.out.print("Input was invalid. Try again: ");
input.next(); // skip the invalid input
}
}
System.out.print(diameter);

最新更新