-4

http://ideone.com/HqKVDt

I have the following code:

 while (true) {
     if (flag == 0) {
        System.out.println("1. Display all staff");
        System.out.println("2. Clear schedule");
        System.out.println("3. Display schedule");
        System.out.println("4. Assign shift to casual employee");
        System.out.println("5. Assign shifts to permanent employee");
        System.out.println("6. Calculate total weekly wages");
        System.out.println("7. Exit Program");

        while (true) {
            System.out.println("Enter your selection");
            Scanner in = new Scanner(System.in); // in these lines
            n = in.nextInt();   // in these lines
            if (n <= 0 || n > 7) {
                System.out.println("Invalid Selection - must be between 1 and 7.");
                break;
            }
        }
    }

Now, whenever I run the program, it gives me the following compilation error:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at EmployeeDriverSystem.main(Main.java:61) 

Line 61 is the line with the comment "in these lines"

Harry Lewis
  • 171
  • 2
  • 11

1 Answers1

1

You posted this code some time back. What you've not now mentioned is that you're trying to run it on ideone where the execution is not paused for user input, instead you have to pass the standard input before running the program. Try this on your computer in a console and it will run without and hassles any with no NoSuchElementException.

You're getting user input in an infinite while loop on ideone. It will not work as expected because you cannot provide infinite input beforehand unless you provide the input for exit condition in the end.

EDIT

As an example for people who downvote for no reason: http://ideone.com/dmBMJO
You get java.util.NoSuchElementException because standard input is empty.

Abdul Fatir
  • 6,159
  • 5
  • 31
  • 58
  • Care to explain the downvote? – Abdul Fatir Jun 02 '16 at 12:52
  • I haven't voted, but I guess the voter thinks that this should be a comment. Even though it looks like the correct explanation to OPs problem and therefore is a valid answer. (btw: I wrote that before your edit, but forgot to commit it :P) – Tom Jun 02 '16 at 14:54
  • @Tom Yes, I saw that in your comment. :D About the down-vote, people should at least be courteous enough to mention the reason. – Abdul Fatir Jun 02 '16 at 15:23
  • Well some users don't do that anymore, because they experienced revenge downvotes by the downvoted user, instead of having a mature discussion about the downvoted post and what should be improved. Kind of a bad situation for both sites. – Tom Jun 02 '16 at 15:32