1

How do I exit this loop when user presses ENTER. This is part of the codes I have done. I am having problems in how to code when user presses ENTER.

static String[] itemList = new String[10];

do {
    System.out.print("Enter item (press ENTER to exit) " + (count + 1) + ":  ");
    String item = input.next();
    itemList[count] = item;
    if (item == "")
        count = itemList.length;
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
cjmalacaman
  • 15
  • 2
  • 7

4 Answers4

3

You are comparing Strings using == not .equals().

This compares the pointer to the String, not the contents of the String.

Tim B
  • 40,716
  • 16
  • 83
  • 128
  • 1
    He means you have to use `String#equals` to compare strings, not `==`: `item.equals("")`. `==` compares references, not content. Please read some Java tutorial about strings. – m0skit0 Feb 11 '14 at 09:40
  • @m0skit0 sorry i still don't quite understand. i just started learning programming for my course – cjmalacaman Feb 11 '14 at 09:43
0
Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();
while(readString!=null)
{
    System.out.println(readString);
    if(readString.equals(""))
        System.out.println("Read Enter Key.");
    if(scanner.hasNextLine())
        readString = scanner.nextLine();
    else
        readString = null;
}
RaceBase
  • 18,428
  • 47
  • 141
  • 202
0

Check the condition before entering into loop. For example:

boolean statusIsNotReady = true;
while(statusIsNotReady) {
    // do your fty;
    if(someCondition) {
        statusIsNotReady = false; // If the status changed
    }
}
Ashot Karakhanyan
  • 2,804
  • 3
  • 23
  • 28
0
public class SampleInputReader{
    public static void main(String args[]){

    String[] itemList = new String[10];
            int count = 0;
            Scanner keyboard = new Scanner(System.in);
            String data = "";

            do{
                    System.out.print("Enter item (press ENTER to exit) " + (count + 1)+ ":  ");
                    data = keyboard.nextLine();
                    if(data.isEmpty())
                        break;

                      itemList[count] = data;
                      count++;
            }while(true); 

            for(int i = 0; i< itemList.length; i++)
                System.out.println(itemList[i]);

}
}

But instead of Array i suggest you to use Arraylist.

kumar
  • 691
  • 1
  • 7
  • 16