How to exit loop with ENTER

吃可爱长大的小学妹 提交于 2019-12-24 14:04:00

问题


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;

回答1:


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

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




回答2:


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



回答3:


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



回答4:


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.



来源:https://stackoverflow.com/questions/21698038/how-to-exit-loop-with-enter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!