Reputation: 171
I've been working to improve my java skills but still having trouble with some stuff. For this one program, everything seems to be functioning properly except my final output. Essentially, once it reads in numbers.txt, it is supposed to put the values into an array and then print out the largest number. There must be a flaw in my logic however, as currently it is only outputting the top number in the list rather than finding the largest number. Here is my program and I put a comment where I think my logic is flawed.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ProcessDataFile {
public static void main(String[] args) throws IOException {
String fileName = "numbers.txt";
String temp;
int max = Integer.MIN_VALUE;
int i = 0;
int[] numbers = new int[100000];
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
while ((temp = br.readLine()) != null) {
if (temp.isEmpty())
break;
numbers[i++] = Integer.parseInt(temp);
}
}
// I think my logic error is somewhere in this section.
for (i = 0; i < numbers.length; i++)
if (max < numbers[i])
max = numbers[i];
System.out.println("The largest number is: " + max);
}
}
Upvotes: 0
Views: 2115
Reputation: 46834
The problem is in your numbers.txt file. Will depend what platform you are on and what line ending it is expecting, but I believe that the code works.
Im running this code on a Mac, In IntelliJ with a txt file containing random numbers. It must be triggering the temp.isEmpty() condition and exiting after it has read the first item.
Check the file, particularly the line endings.
Also, if you can't step through the code in debug mode, try adding some System.out.println statements to clarify what is happening.
This code works for me.
Upvotes: 0
Reputation: 26971
Yes, theres an error but not in your logic, yore missing for
brackets, so just first line after for
is inside the iteration. Look your code with correct identation
// I think my logic error is somewhere in this section.
for (i = 0; i < numbers.length; i++)
if (max < numbers[i])
max = numbers[i]; // this line is out of the for scope!!!
Just add the {
and }
to define loop scope
// I think my logic error is somewhere in this section.
for (i = 0; i < numbers.length; i++){
if (max < numbers[i])
max = numbers[i];
}
Upvotes: 1