我试图确保用户输入的是数字而不是单词。我该怎么做?我试过了,但是当我输入数字时,它仍然说它是一个字符串。
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while(true) {
System.out.println("What is the diameter of the sphere (cm): ");
var diameter = input.next();
if (diameter instanceof String) {
System.out.println("Please enter a number");
} else {
break;
}
}
}
}
答案 0 :(得分:0)
当使用 InputMismatchException
系列函数(Boolean、Byte、Double、Float、Int、Line、Long、Short)调用时,不正确的输入将抛出 input.next*
类型的异常。
如果您需要特定类型,请使用该版本的函数并将其包装在 try-catch 块中:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while(true) {
System.out.println("What is the diameter of the sphere (cm): ");
try {
var diameter = input.nextFloat();
break;
} catch(InputMismatchException e) {
System.out.println("Please enter a number");
}
}
}
答案 1 :(得分:0)
每个键盘输入都是一个字符串。如果您需要一个数字,则需要对其进行转换。由于您使用的是扫描仪,因此 input.nextInt()
会为您执行此操作(如果输入不可解析为数字,则会引发异常)。还有 input.hasNextInt()
,它会消耗一些输入并告诉你它是否是一个整数,在这种情况下 nextInt()
不会抛出。
您还可以使用 Integer.parseInt()
将 String
转换为整数(同样,如果输入不是数字,这将引发异常)。
(当然其他数字类型也有这些函数的对应版本)
答案 2 :(得分:0)
".next()" 是一个字符串。如果你想要双重使用“.nextDouble”。使用 try catch 代替 if 语句,如果用户输入错误的数据类型,它将捕获异常。
import java.util.*;
import java.util.InputMismatchException;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double diameter;
while (true) {
System.out.print(
"What is the diameter of the sphere (cm): ");
try {
diameter = input.nextDouble();
break;
} catch (InputMismatchException mme) {
System.out.println("double value not entered");
// clear the scanner input
input.nextLine();
}
}
System.out.println("The diameter is " + diameter);
}
}
信用:@WJS