Scanner scanner = null;
try {
Scanner myfile = new Scanner(new File("postfix.txt"));
while (myfile.hasNext()) {
input = myfile.nextLine();
inputArray = input.split(" ");
if (inputArray.length == 3) {
inputArray = input.split(" ");
Double number1 = Double.parseDouble(inputArray[0]);
Double number2 = Double.parseDouble(inputArray[1]);
String operator = inputArray[2];
try {
switch (operator) {
case "+":
result = number1 + number2;
break;
case "-":
result = number1 - number2;
break;
case "/":
result = number1 / number2;
break;
case "*":
result = number1 * number2;
break;
default:
System.out.println("Received unsupported operator: "
+ operator);
break;
}
System.out.println("Your expression is:" + number1
+ operator + number2);
System.out.println("Your answer is: " + result);
} catch (NumberFormatException e) {
System.err.println("Invalid expression");
continue;
}
}
}
} catch (FileNotFoundException e) {
System.out.println("Your file is not found: -" + e.getMessage());
}
文字就像这样
44 3 +
9.99 + 0.09
12 0 *
. 10 -
10.2 2 *
12 4 /
66.1 0.12 -
.0 99.10 +
300 4.0 +
* 20 10 /
10 20
5.2 +
1 2 &
100 139 -
- 80 2
9 5 2
4 / 3
3 A -
200.5 10 *
2 * 4
8 2 *
10 20 -
8 16 /
-4 12 +
+ 4 2
x y z
表达式:
Please enter your file name:
所有上述表达式都应该解决,但是那些表达式如下:
x y z, + 4 2
应该提出无效的表达。
当我运行我的代码时,文本中只有一个表达式被解析。之后,它会出现无效的表达,但不会继续阅读文本。此外,它需要要求用户键入文件名并从中读取,但此刻它只从系统中已有的文件中读取。
答案 0 :(得分:0)
主要问题是你问的文件的第二行 双倍运算符,你有双运算符双
9.99 + 0.09
以防止使用try chatch
停止解析程序设置
try{...
解析之前
用于从控制台读取文件名
Scanner lineScanner = new Scanner(System.in);
System.out.println("Please enter your file name: ");
String path = lineScanner.nextLine();
Scanner myfile = new Scanner(new File(path));....
答案 1 :(得分:0)
这里试试这个,
Scanner scanner = null;
try {
Scanner myfile = new Scanner(new File("postfix.txt"));
while (myfile.hasNext()) {
String input = myfile.nextLine();
inputArray = input.split(" ");
if (inputArray.length == 3) {
inputArray = input.split(" ");
String operator = null;
Double number1 = null;
Double number2 = null;
try {
number1 = Double.parseDouble(inputArray[0]);
number2 = Double.parseDouble(inputArray[1]);
operator = inputArray[2];
} catch (NumberFormatException numberFormatException) {
continue;
}
try {
switch (operator) {
case "+":
result = number1 + number2;
break;
case "-":
result = number1 - number2;
break;
case "/":
result = number1 / number2;
break;
case "*":
result = number1 * number2;
break;
default:
System.out.println("Received unsupported operator: "
+ operator);
break;
}
System.out.println("Your expression is:" + number1
+ operator + number2);
System.out.println("Your answer is: " + result);
} catch (NumberFormatException e) {
System.out.println("Invalid expression");
}
}
}
} catch (FileNotFoundException e) {
System.out.println("Your file is not found: -" + e.getMessage());
}
我确信有些东西仍然缺失,因为我完全无法理解你的问题。
明确说明您想要获得的条件。
然后使用上面的代码。
问候。
答案 2 :(得分:0)
NumberFormatException
的try和catch块没有包装解析字符串为double的正确代码块。
移动try {
try {
switch (operator) {
要
try {
Double number1 = Double.parseDouble(inputArray[0]);
保护正确的代码块。