Skip to content
Advertisement

Verifying multiple tokens as Ints with Java

/* My goal is to use the terminal to receive 2 integers and add them together in a Java program. I need to confirm that both terminal entries are ints. If the are, I should proceed to add the ints together. If not, I should print out “Invalid input entered. Terminating…”

I am trying to use an if statement with hasNextInt(), but my program is only verifying the first Scanner input. How do I confirm both Scanner inputs are ints? Any help would be appreciated.

Here is my Java code: */

JavaScript

Advertisement

Answer

You already read the int if it’s available and basically, you’ll just have to repeat this step. You can use an additional flag to indicate whether the program was able to read the two ints successfully:

JavaScript

Update

Complete example:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement