Created
July 1, 2012 07:55
-
-
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"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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