-1

Having an issue with my do while loop as it doesn't end when STOP is entered. Also I'm not sure if I need to add any exceptions or what not. I know doing toString would be more efficient but the requirement for the program is a for loop when extracting the output.

import java.util.*;
import java.util.ArrayList;
import java.lang.IndexOutOfBoundsException;
public class MyProj
{

    public static void main(String[] args)
    {
        ArrayList <String> MyItems = new ArrayList <String>();
        Scanner Scan = new Scanner(System.in);
        String Temp;
        System.out.println("Please enter the name of an object, repeat as needed, type STOP to end");

            do
            {
                Temp = Scan.nextLine();
                if(Temp != "STOP")
                {
                MyItems.add(Temp);
                }
            }
            while(Temp == "STOP");

        for(int x = 0; x <= MyItems.size() - 1; x++)
        {
            System.out.println(MyItems.get(x));
        }



    }
}
  • 2
    `while(!temp.equalsIgnoreCase("stop"));` Also you can't compare string with `==` in java... that will compare their memory address. instead use `.equals(String another)` or what i just used in the above example – 3kings Sep 10 '16 at 01:14
  • Thank you, very appreciated. – Tyler Thompson Sep 10 '16 at 01:21
  • Possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Ole V.V. Sep 10 '16 at 02:44

1 Answers1

1

Try this code:

do
{
    Temp = Scan.nextLine();
    if(!Temp.equals("STOP"))
    {
        MyItems.add(Temp);
    }
}
while(!Temp.equals("STOP"));

I'd recommend that you change that to equalsIgnoreCase() as @3kings suggested.

Hele
  • 1,558
  • 4
  • 23
  • 39