如何检查用户输入的是双精度值?
How can I check that the user is inputing a double?
我试图让用户给我一个数字格式的直径,如果他们输入一个字符串,程序就不会崩溃。这段代码告诉我输入是否为整数,但它仅在您输入两次答案后才有效。我该怎么做才能告诉我第一个用户输入是否为整数?
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();
}
}
假设您想查看该项目是否为双精度(而不是整数),一种方法是使用 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);
你为什么不直接提示输入双打?对于物体的尺寸之类的东西,接受所有双打是合适的。如果要提示输入字符串,请使用 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);
我试图让用户给我一个数字格式的直径,如果他们输入一个字符串,程序就不会崩溃。这段代码告诉我输入是否为整数,但它仅在您输入两次答案后才有效。我该怎么做才能告诉我第一个用户输入是否为整数?
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();
}
}
假设您想查看该项目是否为双精度(而不是整数),一种方法是使用 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);
你为什么不直接提示输入双打?对于物体的尺寸之类的东西,接受所有双打是合适的。如果要提示输入字符串,请使用 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);