Skip to content

Instantly share code, notes, and snippets.

@chestergrant
Created July 1, 2012 07:55
Show Gist options
  • Save chestergrant/3027436 to your computer and use it in GitHub Desktop.
Save chestergrant/3027436 to your computer and use it in GitHub Desktop.
Reads two integers and display them. This is part of "1000 programming exercise by Chess"
import java.util.*;
public class ReadTwoNumbers {
//When reading in digit you need to account for invalid inputs
public static int readNum(String promptMsg, boolean hasPrompt){
boolean isDig = true; //Checks if the value just read in is an integer
int output = -1; //Stores the return value of the read in number
do{
isDig = true;
Scanner input= new Scanner (System.in); //Use to read in the data
//Prompt the user with a message if there is one
if(hasPrompt){System.out.println(promptMsg);}
try{
output = input.nextInt(); //Does the actual reading in of a integer
}catch(Exception ex){
isDig = false; //An error occur and the value is not an integer
}
}while(!isDig);//Keep trying to read an integer until we get valid integers
return output;
}
public static void main(String[] args) {
int num1 = readNum("Enter first number:", true);
int num2 = readNum("Enter second number:", true);
System.out.println ("The first number " + num1 + ".");
System.out.println ("The second number " + num2+ ".");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment