0

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

TryingToCode
  • 31
  • 1
  • 1
  • 7

2 Answers2

0

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.

Mayank Agarwal
  • 376
  • 2
  • 9
0

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());

    }
}