I am trying to read line by line from the file, then compare numbers in that file.
I am unsure why the program is not executing past the if statement, since my first two numbers in the file are as follows:
1
3
6
4
I am expecting increased
value to go up, but it doesn't even hit that point.
public static void numComparison() throws IOException, NumberFormatException {
BufferedReader bufferedReader = new BufferedReader(new FileReader("/Users/WorkAcc/Desktop/file.txt"));
String lines;
LinkedList<Integer> list = new LinkedList<Integer>();
int increased = 0;
while ((lines = bufferedReader.readLine()) != null){
list.add(Integer.parseInt(lines));
}
for (int i = 0; i<=list.size(); i )
if (list.get(i) < list.get(i )){
increased ;
}
else{
continue;
}
}
CodePudding user response:
Two simple changes will make your code work properly.
- First of all,
i
won't be working in this case. Thei
actually changes (increments) the value ofi
. Usei 1
instead to get a new number without alteringi
. - You should also change the end point of your for loop, or you will always get the
IndexOutOfBoundsException
.
This will work:
public static void numComparison() throws IOException, NumberFormatException {
BufferedReader bufferedReader = new BufferedReader(new FileReader("/Users/WorkAcc/Desktop/file.txt"));
String lines;
LinkedList<Integer> list = new LinkedList<Integer>();
int increased = 0;
while ((lines = bufferedReader.readLine()) != null){
System.out.println(lines);
list.add(Integer.parseInt(lines));
}
for (int i = 0; i<list.size()-1; i ){ // -1 so you dont compare the last element of
// your list to an element that doesnt exist
if (list.get(i) < list.get(i 1)){
increased ;
}
else{
continue;
}
}
System.out.println(increased);
}