简体   繁体   中英

Java: while loop for user input not executing

Edit: the problem turned out to be caused by my closing System.in in a previous part of the program, thereby making it unusable later on.

I'm trying to create a loop for user input but it's not functional...

Here's what I've got:

    Scanner userkey = new Scanner(System.in);

    System.out.println("Enter commands");
    while(userkey.hasNext()){

        if (userkey.next().equals("exit")){
            System.out.println("EXIT!!!!");
            break;
        }
        System.out.println("In while loop test");
    }

I guess userkey.hasNext() is return false for some reason...

try this:

import java.util.Scanner;

public class Snippet {
    public static void main(String[ ] args)  
    { 

         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;

                if(readString.equals("exit")){
                    System.out.println("EXIT");
                    break;
                }
            }

    }

}

Even your code should work, but this is a more verbose version.

Try this code:

import java.util.Scanner;
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner userkey = new Scanner(System.in);
        System.out.println("Enter commands");
        do  {
            if (userkey.next().equals("exit")) {
                System.out.println("EXIT!!!!");
                break;
            }
            System.out.println("In while loop test");
        }while(userkey.hasNext());

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM