我是java初学者,遇到一个问题:在下面程序中,当用户输入num1和num2时,如果用户输入错误,例如输入字母【k】,就会报错,这应该怎么判断啊?请高手教教我,谢谢!
import java.util.Scanner;
public class FloatNumber {
public static void main(String[] args) {
double num1, num2;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the num1 and num2: ");
num1 = scan.nextDouble();
num2 = scan.nextDouble();
System.out.println("The " + num1 + " and the " + num2 + " sum is "
+ (num1 + num2));
if (num1 >= num2) {
System.out.println("The " + num1 + " and the " + num2
+ " differ is " + (num1 - num2));
} else {
System.out.println("The " + num1 + " and the " + num2
+ " differ is " + (num2 - num1));
}
System.out.println("The " + num1 + " and the " + num2 + " multiply is "
+ num1 * num2);
}
}
------解决方案--------------------
try catch
------解决方案--------------------
hasNextDouble()
------解决方案--------------------
正则表达式
String str = "48979835"; //你输入的字符
String reg = "[0-9]*"; //正则表达式
str.matches(reg)); //这句就是匹配,判断它
------解决方案--------------------
num1 = scan.nextDouble();
num2 = scan.nextDouble(); 这个是接受所输入的字符的 用nextDouble() 当然不能接受 英文字母啦
------解决方案--------------------
------解决方案--------------------
我的建议是你不用nextdouble,用字符串的形式取出来。再判断
------解决方案--------------------
用正则表达式!!!!!
------解决方案--------------------
- Java code
public static void main(String[] args) { Scanner scan = new Scanner(System.in); double num1, num2; try { num1 = scan.nextDouble(); num2 = scan.nextDouble(); System.out.println(num1 + " " + num2); } catch (InputMismatchException e) { // e.printStackTrace(); // DO WHATEVER YOU WANNA DO // IF ERROR HAPPENS System.out.println("Input Error!"); } }
------解决方案--------------------
你的代码本来就会报错的!!!!!!
想更详细一点,就加上try catch,打印出错信息,比如"请输入纯数字"之类的.