0

I have a minor problem with my Java snippet. I want to take a double or int and print an error message and reloop with any other input. Now, I'm fairly new to Java, so this may not be the most efficient way of achieving this, but what can you do?

In any case, the issue I'm having is that if I enter an invalid input, it prints my error message twice before accepting a new input. I would just use sc.next(), but I don't want to accept another invalid input if a user enters a string with spaces.

It has obvious comments because that's what my professor wants, so I do it

Here's my code snippet:

System.out.println("Enter hours worked: ");
                    while(hourFinisher == false)
                    {
                        //avoids type mismatch by allowing double or int to be entered
                        if(sc.hasNextDouble())
                        {
                            hours = sc.nextDouble();
                            isDouble = true;
                            hourFinisher = true;
                        }
                        else if(sc.hasNextInt())
                        {
                            intHours = sc.nextInt();
                            isDouble = false;
                            hourFinisher = true;
                        }
                        //in the case of a non-double or int, prints an error message and accepts a new input
                        else
                        {
                            System.out.println("Invalid Input! Please enter valid input.");
                            sc.nextLine();
                        }

To be clear, what I get when I input, for example 'a', is Invalid Input! Please enter valid input. twice.

I don't want to print that twice; it's redundant. Any pointers are appreciated!

Thanks!

Adam
  • 39
  • 1
  • 8
  • 1
    Possible duplicate of [Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods](http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo) – azurefrog Apr 18 '17 at 21:17

1 Answers1

0

Use sc.nextLine(); after other inputs (i.e. nextInt(), nextDouble(). The input doesn't take automatically after these.

stinepike
  • 50,967
  • 14
  • 89
  • 108