[英]java won't break up a user input with multiple double and char variables using Scanner and System.in
我希望用戶使用以下變量之一輸入數學方程式:*,/,+,-
輸入示例(不帶空格):2 * 2、35.7 / 3、4.5 + 5.5
然后,我想將第一個數字,char變量和第二個數字分開,並將它們存儲到單獨的變量中。
當我使用此代碼時:
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();
}
}
我收到此錯誤/響應:
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)
我真的很想使用這樣的東西:
operator = s.next("[*,/,+,-]").charAt(fnum + 1);
請幫助,我不知道我在做什么錯。
nextDouble
讀取直到下一個空格。 由於您按給定的方式指定了整個輸入而沒有任何空格,因此它將失敗(例如,因為2*2
不是有效的Double
值)。
如果您不需要任何空格,則可以簡單地讀取整行,然后對其進行解析:
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();
}
請注意, split
期望使用正則表達式,因此它基本上采用輸入字符串,並根據出現的任何運算符(如您的問題中所定義的那樣)對它進行分割。 如果輸入有效,則結果將是具有兩個double值的數組。
當然,用輸入有效性檢查將它們包裝起來是一個好主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.