0

The program that I have written below was designed so that if a user doesn't enter an integer when prompted, the program will loop until they do. This works for the initial check, but the second check does not work. The code is as follows:

import java.util.Scanner;
public class SafeInput
{
    public static void main(String[]args)
    {
        System.out.println("Please enter any integer. If you want to exit, enter -1>");
        Scanner scan = new Scanner(System.in);

        while(!scan.hasNextInt())
        {
            String garbage = scan.nextLine();
            System.out.println("You've entered garbage.");
        }

        int input = scan.nextInt();

        while(input != -1)
        {           
            System.out.println("\nYou entered: "+input);
            System.out.println("Please enter any integer. If you want to exit, enter -1>");

            while(!scan.hasNextInt())
            {
                System.out.println("You've entered garbage.");
                String garbage1 = scan.nextLine();
            }

            input = scan.nextInt();
        }

        System.out.println("-1 entered. Goodbye");
    }
}

Here's what happens when I execute the program:

Please enter any integer. If you want to exit, enter -1>
this is a string
You've entered garbage.
1

You entered: 1
Please enter any integer. If you want to exit, enter -1>
2

You entered: 2
Please enter any integer. If you want to exit, enter -1>
this is also a string
You've entered garbage.
You've entered garbage.
string
You've entered garbage.
1

You entered: 1
Please enter any integer. If you want to exit, enter -1>
2

You entered: 2
Please enter any integer. If you want to exit, enter -1>
-1
-1 entered. Goodbye

Why is it that when I fail the second check for an integer, the program outputs:

You've entered garbage.
You've entered garbage.

Instead of:

You've entered garbage.

Thanks!

user1803551
  • 11,914
  • 5
  • 39
  • 63
Zampanò
  • 402
  • 1
  • 8
  • 25

2 Answers2

0

second while loop should be updated like below.

        while(input != -1)
        {           
            System.out.println("\nYou entered: "+input);
            System.out.println("Please enter any integer. If you want to exit, enter -1>");
            scan.nextLine();
            while(!scan.hasNextInt())
            {
                System.out.println("You've entered garbage");
                String garbage1 = scan.nextLine();
            }

            input = scan.nextInt();
        }
Heshan
  • 162
  • 8
  • This works perfectly! Thank you! Why exactly does this work, though? How does this solve the problem? – Zampanò Jan 17 '16 at 18:02
  • Please refer http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods and this explains the issue of using scan.nextLine() after scan.NextInt() – Heshan Jan 18 '16 at 03:37
0

use next() instead of nextLine().

     while(input != -1) {           
                System.out.println("\nYou entered: "+input);
                System.out.println("Please enter any integer. If you want to exit, enter -1>");

                while(!scan.hasNextInt())
                {
                    System.out.println("You've entered garbage.");
                    String garbage1 = scan.next();
                }

                input = scan.nextInt();
}

Look at Scanner#nextLine() java doc,

This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

See code

Debug:

while(input != -1)
    {           
        System.out.println("\nYou entered: "+input);
        System.out.println("Please enter any integer. If you want to exit, enter -1>");

        while(!scan.hasNextInt())
        {
            System.out.println("-- Second -- ");
            System.out.println("You've entered garbage.");
            String garbage1 = scan.nextLine();
            System.out.println(" garbage1 -> " + garbage1);
        }

        input = scan.nextInt();
    }

Output:

Please enter any integer. If you want to exit, enter -1>
q
-- First -- 
You've entered garbage.
1
 -- input --1

You entered: 1
Please enter any integer. If you want to exit, enter -1>
aa
-- Second -- 
You've entered garbage.
 garbage1 -> 
-- Second -- 
You've entered garbage.
 garbage1 -> aa
ab
-- Second -- 
You've entered garbage.
 garbage1 -> ab

Just for fun I did some 'enhanced' implementation. It should work correctly.

package example;

    import java.util.Scanner;

    public class SafeInput {

        public static void main(String[] args) {
            System.out.println("Please enter any integer. If you want to exit, enter -1>");
            try (Scanner scan = new Scanner(System.in)) {
                while (true) {
                    int input = 0;
                    String garbageOutput = null;
                    if (scan.hasNextInt() && ((input = scan.nextInt()) != -1)) {
                        System.out.println("\nYou entered: " + input);
                        System.out.println("Please enter any integer. If you want to exit, enter -1>");
                    } else if (scan.hasNextInt() && ((input = scan.nextInt()) == -1)) {
                        System.out.println("-1 entered. Goodbye");
                        break;
                    } else if (!scan.hasNextInt() && (scan.hasNextLine())
                            && (!(garbageOutput = scan.nextLine()).isEmpty())) {
                        System.out.println(String.format("You've entered garbage - [%s]", garbageOutput));
                    }
                }

            }

        }

    }
bodo
  • 599
  • 4
  • 16
  • This only fixes part of the problem. During the second check, the program will only output: "You've entered garbage" once if I enter a single word string. Multiple word strings will still result in the program outputting: "You've entered garbage. You've entered garbage." – Zampanò Jan 17 '16 at 18:00
  • See the new implementation, it should work correctly. – bodo Jan 17 '16 at 19:16