我如何检查如果两个用户输入仅包含数字(计算器程序),我不断收到运行时错误
嗨,我对java还是个新手,我想知道如何检查用户是否只输入数字而不是字母当我必须将输入从字符串解析为双精度以便能够将小数相加在一起时,我的问题就出现了安慰。但是当我用谷歌搜索如何检查我的输入是否只是数字时,我必须接受一个字符串输入,该字符串输入给我*2个输入(希望我说得通)。是否有一个更简单的版本可以做到这一点,或者我是缺少一些东西。
public class javaCalculator {
public static void main(String[] args){
//initializing two scanners for numbers and operations and creating 3 variables
Scanner numbers = new Scanner(System.in);
Scanner operation = new Scanner(System.in);
double number1;
double number2;
String operator;
//getting user input for the type of operations and numbers they want to enter
System.out.print("Enter the operator you would like to choose(+, -, *, /): ");
operator = operation.next();
//My program didn't want to take decimals, so I had to parseDouble which takes the input as a string and then
//converts(parse) it to a double which then makes my program run with decimal numbers
System.out.print("Enter the first number: ");
String num1 = numbers.nextLine();
number1 = Double.parseDouble(numbers.nextLine());
System.out.print("Enter your second number: ");
String num2 = numbers.nextLine();
number2 = Double.parseDouble(numbers.nextLine());
boolean check1 = num1.matches("[0-9]+");
boolean check2 = num2.matches("[0-9]+");
if (check1 == true && check2 == true){
System.out.println("...");
}else {
System.out.println("Only enter numbers not letters.");
}
//Using if else statements to check what operation was chosen above and then depending on
//that choice(+, -, *, /) printing a suitable answer to console
//Creating a calculation variable to use in the writing to a file
String calculation;
if (operator.equals("+")){
calculation = (number1 + " + " + number2 + " = " + (number1 + number2));
System.out.println(calculation);
}else if (operator.equals("-")){
calculation = (number1 + " - " + number2 + " = " + (number1 - number2));
System.out.println(calculation);
}else if (operator.equals("*")){
calculation = (number1 + " * " + number2 + " = " + (number1 * number2));
System.out.println(calculation);
}else if (operator.equals("/")){
calculation = (number1 + " / " + number2 + " = " + (number1 / number2));
System.out.println(calculation);
}else{
calculation = operator + ":" + " Is not a valid operator!";
System.out.println(calculation);
}
Hi I'm still new to java and I would like to know how to check if the user only input numbers and not letters my problem comes in when I had to parse the input from string to double to be able to add decimals together in the console. But when I googled to see how to check if my input is only numbers I had to take in a string input that gives me *2 inputs(hope I'm making sense).Is there maybe a easier version to do this or am I missing something.
public class javaCalculator {
public static void main(String[] args){
//initializing two scanners for numbers and operations and creating 3 variables
Scanner numbers = new Scanner(System.in);
Scanner operation = new Scanner(System.in);
double number1;
double number2;
String operator;
//getting user input for the type of operations and numbers they want to enter
System.out.print("Enter the operator you would like to choose(+, -, *, /): ");
operator = operation.next();
//My program didn't want to take decimals, so I had to parseDouble which takes the input as a string and then
//converts(parse) it to a double which then makes my program run with decimal numbers
System.out.print("Enter the first number: ");
String num1 = numbers.nextLine();
number1 = Double.parseDouble(numbers.nextLine());
System.out.print("Enter your second number: ");
String num2 = numbers.nextLine();
number2 = Double.parseDouble(numbers.nextLine());
boolean check1 = num1.matches("[0-9]+");
boolean check2 = num2.matches("[0-9]+");
if (check1 == true && check2 == true){
System.out.println("...");
}else {
System.out.println("Only enter numbers not letters.");
}
//Using if else statements to check what operation was chosen above and then depending on
//that choice(+, -, *, /) printing a suitable answer to console
//Creating a calculation variable to use in the writing to a file
String calculation;
if (operator.equals("+")){
calculation = (number1 + " + " + number2 + " = " + (number1 + number2));
System.out.println(calculation);
}else if (operator.equals("-")){
calculation = (number1 + " - " + number2 + " = " + (number1 - number2));
System.out.println(calculation);
}else if (operator.equals("*")){
calculation = (number1 + " * " + number2 + " = " + (number1 * number2));
System.out.println(calculation);
}else if (operator.equals("/")){
calculation = (number1 + " / " + number2 + " = " + (number1 / number2));
System.out.println(calculation);
}else{
calculation = operator + ":" + " Is not a valid operator!";
System.out.println(calculation);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码尝试读取相同的数字两次:
您应该做的是将数字作为字符串读取,确认它是一个数字,然后仅在匹配时才解析它。
或者,您可以简单地尝试直接解析字符串并捕获异常,即
Your code is trying to read the same number twice:
What you should do is read the number as a string, confirm that it is a number and then parse it only if it matches.
Alternatively you can simply try to parse the string directly and catch the exception i.e.
你的做法没问题。尽管 Scanner lib 提供了 nextDouble() 方法,但我建议使用您正在使用的正则表达式控件。尽管有一些小问题需要修复:
您首先解析(从字符串转换为双精度),然后检查格式。例如,如果用户输入一个字母,当 parseDouble 尝试将字符串转换为双精度时,程序将失败。因此,从输入中读取字符串,应用匹配控制,如果没有错误则解析。
您的正则表达式匹配任何包含 1 个或多个数字的字符串。例如,输入 Hello1 将匹配,因为至少有一个数字。那么解析将会失败,因为 Hello1 不是一个有效的数字。您必须使用仅匹配数字的正则表达式。该表达式如下所示:"^[0-9]+$"
^ 字符表示该表达式必须在行首匹配,$ 字符强制该表达式在行首处匹配该行的末尾。换句话说,该表达式应该从字符串的开头到结尾都有数字。添加 .trim() (num1.trim().matches("[0-9]+");) 来删除开头或结尾的任何额外空格是一件好事。
第三个建议是,如果您不想使用小数,则 Double 类型可能不是正确的数据类型。 Double 可以表示小数。正确的类型应该是整数。
number1 = Integer.parseInt(num1);
@christopher 当您引发错误时,您正在打印一条消息,但程序仍在运行。这就是为什么您会在 @Turamarth 解决方案评论中收到错误评论
Your approach is OK. Although Scanner lib provides the nextDouble() method I recommend using the regular expression control you are using. Even though there are some little things to fix:
You are parsing (convert from String to double) first, and then checking format. If for example, the user enters a letter your program will fail when parseDouble tries to convert the String to double. So, read the String from the input, apply the match control, and if there is no Error then parse.
Your regular expression is matching any String that has 1 or more numbers. For example, the input Hello1 will match because there is at least one number. Then the parse will fail because Hello1 is not a valid number. You have to use a regular expression that matches only numbers. This expression will look like this: "^[0-9]+$"
The ^ character means that the expression must match at the beginning of the line, and the $ character force that the expression match at the end of the line. In other words, this expression should have numbers from the beginning to the end of the string. It would be a good thing to add a .trim() (num1.trim().matches("[0-9]+");) to delete any extra white space at the beginning or at the end.
The third recommendation is that if you don't want to use decimals may be Double type is not the proper data type to use. Double can represent decimals. The proper type should be Integers.
number1 = Integer.parseInt(num1);
@christopher When you raise error you are printing a message but the program keeps running. That's why you get the Error commented on @Turamarth solution comment