0

I have been trying to figure out how to analyze wether an inputed variable is a number or a phrase, and then output an appropriate response.

System.out.println("Enter the number of lines in your triangle and pyramid");
lines = input.nextInt();
if (lines != int)

Any ideas?

Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399

1 Answers1

1

Scanner requires you to check the kind of input it sees before you call the nextXyz method.

if (lines != int)

Once you call nextInt(), it is too late to check what kind of input you have: in order for nextInt to succeed, there must be an int available at the current point; otherwise an exception would be thrown.

Use hasNextInt method to check what you have at the current point in the input buffer:

if (input.hasNextInt()) {
    lines = input.nextInt();
} else {
    System.out.println("Please enter a number");
    input.nextLine(); // Drop the current input up to the end-of-line marker
}
Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399