我有如下文本文件,每个部分有2个部分PLUS和MINUS以及2个问题。我想写一个程序来解决它们。我附上了我的代码,因为我无法使用MINUS药水。我为Minus得到的结果仍然是使用Plus运算符。
math.txt
[Plus]
Question = 0
num1 = 2
num2 = 3
Question = 1
num1 = 4
num2 = 5
[Minus]
Question = 0
num2 = 6
num1 = 5
Question = 1
num2 = 7
num1 = 2
CODE :
BufferedReader in = null;
InputStream fis;
try {
fis = new FileInputStream(file);
in = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = in.readLine()) != null) {
String[] file_Array = line.split(" = ");
if (file_Array[0].equalsIgnoreCase("num1")) {
num1 = file_Array[1];
} else if (file_Array[0].equalsIgnoreCase("num2")) {
num2 = file_Array[1];
int sum = Integer.parseInt(num1) + Integer.parseInt(num2);
System.out.println("Answer :" + sum);
}
else if (file_Array[0].equalsIgnoreCase("[Minus]")) {
if (file_Array[0].equalsIgnoreCase("num2")) {
num2 = file_Array[1];
} else if (file_Array[0].equalsIgnoreCase("num1")) {
num1 = file_Array[1];
int minus = Integer.parseInt(num2) - Integer.parseInt(num1);
System.out.println("Answer :" + minus);
}
}
}
} catch (IOException ex) {
System.out.println("Input file " + file + " not found");
}
答案 0 :(得分:-1)
我的解决方案如下:
public static void main(String arg[]) {
BufferedReader in = null;
InputStream fis;
String file = "math.txt";
try {
fis = new FileInputStream(file);
in = new BufferedReader(new InputStreamReader(fis));
String line = null;
String section=null;
String num1 = null;
String num2 = null;
while ((line = in.readLine()) != null) {
String[] file_Array = line.split(" = ");
if (file_Array[0].equalsIgnoreCase("[Minus]"))
{
section="Minus";
}
if (file_Array[0].equalsIgnoreCase("[Plus]"))
{
section="Plus";
}
if (file_Array[0].equalsIgnoreCase("num1")) {
num1 = file_Array[1];
} else if (file_Array[0].equalsIgnoreCase("num2")) {
num2 = file_Array[1];
}
//Solution depends on the fact that there will be a blank line
//after operands.
if (file_Array[0].equals("")){
printResult(section,num1,num2);
}
}
//There is no blank line at the end of the file, so call printResult again.
printResult(section,num1,num2);
} catch (IOException ex) {
System.out.println("Input file " + file + " not found");
}
}
private static void printResult(String section,String num1,String num2) {
if (section.equals("Minus")){
int minus = Integer.parseInt(num2) - Integer.parseInt(num1);
System.out.println("Answer :" + minus);
}
if (section.equals("Plus")){
int sum = Integer.parseInt(num1) + Integer.parseInt(num2);
System.out.println("Answer :" + sum);
}
}