Scanner scanner = new Scanner(System.in);
String expression = scanner.nextLine();
String matches = new Boolean(expression.matches("\\d+")).toString();
switch (matches) {
case "true":
System.out.println("IT'S a number");
break;
case "false":
System.out.println("NOT a number");
}
scanner.close();
# 3 楼答案
这就是我向一些同学询问并静静思考的解决方案
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner entry = new Scanner(System.in);
String myNumber;
int tf;
myNumber = entry.next();
try {
Double.parseDouble(myNumber);
tf = 1;
}
catch (Exception e) {
tf = 0;
}
switch(tf) {
case 1:
System.out.println("Is a number");
break;
default:
System.out.println("No es un número");
break;
}
}
感谢社区如此友善
# 4 楼答案
您需要检查^{中的每个字符。像这样的东西可能会管用
static boolean isNumber(String s) {
if (s == null) {
// Debatable.
return false;
}
int decimalCount = 0;
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
// These are all allowed.
break;
case '.':
if (i == 0 || decimalCount > 0) {
// Only allow one decimal in the number and not at the start.
return false;
}
decimalCount += 1;
break;
default:
// Everything else not allowed.
return false;
}
}
return true;
}
# 1 楼答案
在Java7之前,您可以使用
switch(String)
语句但是在这里,你已经有足够的
switch(int)
和一些解决方法:# 2 楼答案
我提出了一个较短的代码,但它使用正则表达式,如果Halo只是从Java开始,他可能还没有看到这个主题。但它也回答了这个问题,所以这里是:
# 3 楼答案
这就是我向一些同学询问并静静思考的解决方案
感谢社区如此友善
# 4 楼答案
您需要检查^{中的每个字符。像这样的东西可能会管用