基本上我想构建一个 switchcase 语句来检查用户输入是否是整数、 float 或字符串。我想使用 hasCheckInt() 、 hasCheckDouble() 等方法来检查相应的数据类型。
有些代码丢失了,是的,因为我不知道要输入什么。 原谅java菜鸟。
import java.util.Scanner;
public class helloWorld {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
switch()) {
case 1:
if(userInput.hasNextInt()) {
System.out.println("Int");
}
break;
case 2:
if(userInput.hasNextLine()) {
System.out.println("String");
}
break;
}
}
}
最佳答案
Basically I would like to build a switchcase statement if check if a user input is a integer , float or a String. I would like to use methods such as hasCheckInt() , hasCheckDouble() to check the respective datatype.
不能,switch
的 case
必须是常量,而不是表达式(包括函数调用)的结果。
相反,您需要if/else if/else
if (hasCheckInt(argumentHere)) {
// `hasCheckInt` returned `true`
// ...
}
else if (hasCheckDouble(argumentHere)) {
// `hasCheckDouble` returned `true`
// ...
}
else {
// None of the above matched
}
关于java - 使用 switch case 检查用户输入是字符串、整数还是 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24819874/