I'm a beginner in Java Eclipse. I am trying to read a .txt file, and use the data as a String value. However, when I use an if
statement, the condition is not registering the value as a String and is therefore not meeting any conditions and I am only getting the final else
.
The purpose of my code is to read in a text file and determine the required value: i.e. if the line starts with "avg" , the program must display the average of the following numbers.
My .txt file contents is this:
min:1,2,3,4,5,6\n max:1,2,3,4,5,6\n avg:1,2,3,4,5,6
Here is a part of my code:
public static void main(String[] args) throws IOException {
//declare variables
String line, operation;
int min, max, sum, num;
double avg;
List<String> 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
When I manually set operation as "min" or "max" or "avg" the program works as it should.