我是 Java Eclipse 的初学者。我正在尝试读取 .txt 文件,并将数据用作字符串值。但是,当我使用if语句时,条件没有将值注册为字符串,因此不满足任何条件,我只得到最终的else.

我的代码的目的是读取文本文件并确定所需的值:即如果行以 "avg" 开头,则程序必须显示以下数字的平均值。

我的 .txt 文件内容是这样的:

最小值:1,2,3,4,5,6\n 最大值:1,2,3,4,5,6\n 平均值:1,2,3,4,5,6

这是我的代码的一部分:

public static void main(String[] args) throws IOException {

//declare variables

String line, operation;

int min, max, sum, num;

double avg;

List lineArray;

String outputPath = "C:\\output.txt"; //these are not the actual file paths, i just didnt

String inputPath = "C:\\input.txt"; //want to give personal information.

//try open file

try {

//create File instance

File text = new File (inputPath);

Scanner scnr = new Scanner(text);

//loop until end of text file

while ( scnr.hasNextLine() ) {

line = scnr.nextLine(); //read line from text file

operation = line.substring(0,3); //get operation from String data

line = line.substring(4); //get String value of numbers

lineArray = Arrays.asList(line.split(",")); //separate string into array elements

//setup initial values

sum = 0;

min = Integer.parseInt(lineArray.get(0)); //convert to Int

max = Integer.parseInt(lineArray.get(0));

//loop through line array and determine min, sum and max of each

for (int i = 0; i < lineArray.size(); i++ ) {

num = Integer.parseInt(lineArray.get(i));

sum += Integer.parseInt(lineArray.get(i));

if (num > max) max = num;

if (num < max) max = num;

}

avg = sum / lineArray.size();

//the IF condition statement that is not working

if (operation == "min") {

System.out.println(min);

}

else if (operation == "max") {

System.out.println(max);

}

else if (operation == "avg") {

System.out.println(avg);

}

else System.out.println("Error");

} //end of while loop

scnr.close(); //close scanner

} //end of try

catch ( FileNotFoundException e ) {

}

} //end of "main" class

当我手动将操作设置为“min”或“max”或“avg”时,程序会正常工作。