megabyt
megabyt

Reputation: 9

Comparing elements in Integer list in Java

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;
            }
}

Upvotes: 0

Views: 495

Answers (1)

raphaelfachim
raphaelfachim

Reputation: 41

Two simple changes will make your code work properly.

  • First of all, i++ won't be working in this case. The i++ actually changes (increments) the value of i. Use i+1 instead to get a new number without altering i.
  • 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);
}

Upvotes: 1

Related Questions