0

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;
            }
}
3
  • 3
    What do you think list.get(i++) does? Commented Mar 23, 2022 at 18:38
  • @ScottHunter I think it will increment the i to 1 Commented Mar 23, 2022 at 18:41
  • In addition to the i++ issue raised by Scott, your for loop is setup to do list.get() beyond the end of your list. Commented Mar 23, 2022 at 18:44

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.