[英]java won't break up a user input with multiple double and char variables using Scanner and System.in
I want the user to input a math equation using one of these variables: *, /, +, - 我希望用户使用以下变量之一输入数学方程式:*,/,+,-
Input Examples (with no spaces) : 2*2, 35.7/3, 4.5+5.5 输入示例(不带空格):2 * 2、35.7 / 3、4.5 + 5.5
Then I want to break the first number, char variable, and second number apart and store them into separate variables. 然后,我想将第一个数字,char变量和第二个数字分开,并将它们存储到单独的变量中。
When I use this code: 当我使用此代码时:
import java.io.*;
import java.util.Scanner;
class Extra {
public static void main (String[] args) throws IOException {
double fnum, snum;
char operator;
System.out.println("Type Operation.");
Scanner s = new Scanner ( System.in );
fnum = s.nextDouble();
operator = s.next().charAt(fnum + 1);
snum = s.nextDouble();
System.out.println(fnum);
System.out.println(snum);
System.out.println(operator);
s.close();
}
}
I get this error/response: 我收到此错误/响应:
Type Operation.
2*2
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Extra.main(Extra.java:24)
I really want to use something like this: 我真的很想使用这样的东西:
operator = s.next("[*,/,+,-]").charAt(fnum + 1);
Please Help, I don't know what I'm doing wrong. 请帮助,我不知道我在做什么错。
nextDouble
reads until the next whitespace. nextDouble
读取直到下一个空格。 Since you specify your entire input as given without any whitespaces, it fails (since, for example, 2*2
is not a valid Double
value). 由于您按给定的方式指定了整个输入而没有任何空格,因此它将失败(例如,因为
2*2
不是有效的Double
值)。
If you don't want any whitespaces, you could simply read the entire line and then parse it: 如果您不需要任何空格,则可以简单地读取整行,然后对其进行解析:
public static void main(String[] args) {
double fnum, snum;
char operator;
System.out.println("Type Operation.");
Scanner s = new Scanner ( System.in );
String str = s.nextLine();
String[] arr = str.split("[*/+-]");
fnum = Double.parseDouble(arr[0]);
snum = Double.parseDouble(arr[1]);
operator = str.charAt(arr[0].length());
System.out.println(fnum);
System.out.println(snum);
System.out.println(operator);
s.close();
}
Note that split
expects a regex, so it basically takes the input string and split it according to any occurrence of an operator (as defined in your question). 请注意,
split
期望使用正则表达式,因此它基本上采用输入字符串,并根据出现的任何运算符(如您的问题中所定义的那样)对它进行分割。 If the input is valid, the result will be an array with two double values. 如果输入有效,则结果将是具有两个double值的数组。
Of course, it'd be a good idea to wrap these with input validity checks. 当然,用输入有效性检查将它们包装起来是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.