JAVA中如何判断一个输入是数字(小数和整数)还是字符串?
public class Test1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入数值:");
String s = input.next();
if (s != null && s.matches("^[0.0-9.0]+$")) {// [0-9]没办法识别小数,[0.0-9.0]可以识别小数和整数
System.out.println("输入是数字!");
double num = Double.parseDouble(s);
System.out.println(num);
} else {
System.out.println("输入值为字符!");
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入数值:");
String s = input.next();
if (s != null && s.matches("^[0.0-9.0]+$")) {// [0-9]没办法识别小数,[0.0-9.0]可以识别小数和整数
System.out.println("输入是数字!");
double num = Double.parseDouble(s);
System.out.println(num);
} else {
System.out.println("输入值为字符!");
}
}
}