问题描述
- java扫描文件并计算文件中包含的算式
-
怎么用java扫描指定txt,然后计算txt中的算式,比如d:/data.txt,包含算式
12+15-13
33*6 / 6
解决方案
http://blog.csdn.net/lip009/article/details/7768258
解决方案二:
http://ethen.iteye.com/blog/1011402
解决方案三:
import java.io.File;
import java.util.Scanner;
public class T03Scanner {
public static void main(String args[]) throws Exception {
File file=new File("d:\data2.txt");
// create a scanner from the data file
Scanner scanner = new Scanner(file);
// 重复从文件中读取数据
while (scanner.hasNext()) {
int op1,op2,op3,result=0;
String operator1 ="";
String operator2="";
// retrieve each data element
op1 = scanner.nextInt();
operator1 = scanner.next();
op2 = scanner.nextInt();
operator2=scanner.next();
op3=scanner.nextInt();
if (operator1.equals("+")&&operator2.equals("-"))
result = op1 + op2-op3;
if (operator1.equals("-")&&operator2.equals("+"))
result = op1 - op2;
if(operator1.equals("*")&&operator2.equals("/"))
result=op1*op2/op3;
if (operator1.equals("/")&&operator2.equals("+"))
result=op1/op2+op3;
System.out.println("result is " + result);
}
scanner.close(); // also closes the File
}
}
ps(data2.txt)
12 + 15 -13
17 - 18 + 24
33 * 6 / 6
55 / 10 + 2
为什么这样不行
时间: 2025-01-02 08:39:52