-3

The title describes what I am trying to do.

The code doesn't have any errors, but it doesn't output true/false at the right times. For example, for the input

5 1 2 3 4 5 done

the output will be false, which is incorrect because you can see that 5 appears at the end and in another location in the ArrayList. So yeah, I could use some help de-bugging and I appreciate the help!

import java.util.ArrayList;
import java.util.Scanner;

public class LastRunner {

    public static void main (String[] args) 
    {
        Scanner s = new Scanner(System.in);
        
        ArrayList<Integer> list = new ArrayList<>();
        
        System.out.println("Enter some numbers. When done, type \"done\"");
        
        while (s.hasNextInt()) 
        {
            list.add(s.nextInt());
        }
        
        int size = list.size();
        boolean lastChecker = false;
        
        for(int i = 0; i < size-1; i++)
        {
            if (list.get(size-1) == list.get(i))
            {
                lastChecker = true;
            }
        } 
        
        System.out.println(lastChecker);
    }
}

1 Answers1

0

It is plausible that your program works for the input in your question. (As noted in a comment. I have not actually tried it, but I can see why it would work.)

However, there is definitely a bug in your program. The problem I found is here:

     if (list.get(size-1) == list.get(i)) 

The problem is that list.get will return an Integer object. But when you use == to compare two Integer objects, you are actually comparing two object references.

Comparing two Integer values using == only works some of the time. It will depend on the values and how they were created.

The correct way to write the above line is:

    if (list.get(size-1).equals(list.get(i)))

(Note: if you managed to get a null in the list, the above might give you an NPE. However, I would NOT recommend testing for null. A null in your list would be a sign that there was a bug in the code that is building the list. So it is better to let the NPE happen ... so that the programmer will get a bug report, or whatever.)


For a more detailed explanation of why Integer == Integer is incorrect (and why it sometimes works), see the dup link: How to properly compare two Integers in Java?.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216