Set boundaries for integer input - java

I have this small snippet of coding that requires an input from the user when it is ran to determine a certain value. I don't want the user to be able to enter anything less than 0 and anything greater than 1 million, so, 0 =< YEARS_AHEAD =< 1000000.
I've looked through so many tutorials and searched for help on this and found nothing. This is my code.
Scanner reader = new Scanner(System.in);
int YEARS_AHEAD;
System.out.print("Enter the amount of years ahead: ");
while (true)
try {
YEARS_AHEAD = Integer.parseInt(reader.nextLine());
break;
}catch (NumberFormatException nfe) {
System.out.print("This value must be an integer, please enter the number of years ahead again: ");
}

Add a simple if:
if (YEARS_AHEAD < 0 || YEARS_AHEAD > 1000000) {
// say something to the user, retry entering the number
}
Another option is to use the while cycle for this:
int YEARS_AHEAD = -1; // invalid value
while (YEARS_AHEAD < 0 || YEARS_AHEAD > 1000000) {
try {
System.out.print("Enter the amount of years ahead: ");
YEARS_AHEAD = Integer.parseInt(reader.nextLine());
}catch (NumberFormatException nfe) {
System.out.print("This value must be an integer, please enter the number of years ahead again: ");
}
}

Once you have read the input
YEARS_AHEAD = Integer.parseInt(reader.nextLine());
check using if-else whether the input is permitted or not.
if(YEARS_AHEAD < 0 || YEARS_AHEAD >1000000){
System.out.println("Invalid Input");
}else{
// do your processing here.
}

Related

Mortgage calculator, how to exclude letter and accept only numbers

we have this method
System.out.print("Enter Principal Amount (1k to 1m) ") ;
while (true) {
principal = scanner.nextInt();
if (principal >= 1000 && principal <= 1_000_000)
break;
System.out.println("Enter a value between 1k - 1m");
If person puts in letters instead of numbers the error occurs,
I need to get the program to ask the question to put in numbers instead of letter
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Principal Amount (1k to 1m) ") ;
while (true) {
principal = scanner.nextInt();
// if (scanner.nextInt() != NumberFormat??) What should I write in my mortgage calculator that ->
// --> if numbers are not put (for ex. letters) it would print out ("Please enter numbers letters are invalid")
//System.out.println("Please enter numbers");
if (principal >= 1000 && principal <= 1_000_000)
break;
System.out.println("Enter a value between 1k - 1m");
}
The simplest way to do what you want is to wrap the inside of your loop in a try {} block and catch the InputMismatchException
If the input is an int it will process as it does now; if not then instead of carrying on after the Scanner.nextInt() line, java will execute the contents of your catch(InputMismatchException e) { } block
There's an argument that you should validate the input more explicitly, but that will be more complex and for a beginner learning how to catch exceptions is probably more useful.
while (true) {
try {
principal = scanner.nextInt();
if (principal >= 1000 && principal <= 1_000_000)
break;
System.out.println("Enter a value between 1k - 1m");
}
catch (InputMismatchException e) {
System.out.println("Please enter numbers");
}
}
From the comments, the OP replied:
No, if for ex. user enters "abc", I get = Exception in thread "main" java.util.InputMismatchException at java.base/java.util.Scanner.throwFor(Scanner.java:943) at java.base/java.util.Scanner.next(Scanner.java:1598) at java.base/java.util.Scanner.nextInt(Scanner.java:2263) at java.base/java.util.Scanner.nextInt(Scanner.java:2217) at com.petras.Main.main(Main.java:20)
But I want to get the line "Please enter valid number" //not letter and let him put the number again, how should my code look?
The problem is that your code assumes the user will always enter a valid integer value. Instead, as your comment reply indicates, you have to account for invalid inputs by wrapping scanner.nextInt() in a try/catch block
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Principal Amount (1k to 1m) ") ;
int principal = 0;
while (true) {
try {
principal = scanner.nextInt();
} catch(InputMismatchException ime) {
System.out.println("Invalid input: " + principal + ". Please enter an integer value");
continue;
} catch (Exception e) {
// This is most likely a "true" error. Handle accordingly.
}
if (principal >= 1000 && principal <= 1_000_000)
break;
System.out.println("Enter a value between 1k - 1m");
}

How can I remove this java exception error in my code?

When I input a string into the code below by mistake as a test, I get a red java error message in my console. However, within my if statement I added an else part which should end the program if the user doesn't input the if statement condition i.e a number between 0-100. Why this is and how can I fix it?
MY CODE
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int decimal = input.nextInt();
if (decimal > 0 && decimal <= 100) {
//code
}
else {
System.exit(0);
}
When I input a string this message gets displayed. However, I just wanted to tell the user they exerted the wrong value and I wanted the program to quit.
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at MainHandler.main(MainHandler.java:22)
I did try use hasNextInt at one point to try get rid of the exception error but I get an error when I use hasNextInt. https://imgur.com/a/OK8r3RH
Try with something like this. You surround your input inside a try-catch and as long as you get an Exception, you ask the user to put a number again. As soon as the input is valid (a number) you can proceed with your code:
boolean canProceed = false;
int number = -1;
while (!canProceed) {
try {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
number = Integer.parseInt(input.nextLine());
canProceed = true;
} catch (Exception e) {
System.out.println("Invalid input.");
}
}
if (number > 0 && number <= 100) {
System.out.println("That's fine");
}
else {
System.exit(0);
}
You would need double if you are entering decimal numbers and put your code inside try/catch block
try{
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
double decimal = input.nextDouble();
if (decimal > 0 && decimal <= 100) {
}
else {
System.exit(0);
}
}catch (Exception e){
System.out.println(e);
}
Try binding your code inside try and catch blocks like this:
try{
int decimal = input.nextInt();
if (decimal > 0 && decimal <= 100) {
//code
}
else {
System.exit(0);
}
}
catch(Exception e){
System.out.println("You enter wrong value");
}
The code you posted works just fine if the input is provided from the start. However given your "Enter a number:" message I suppose you want the user to provide the input interactively, in which case you'll have to implement a waiting loop :
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
while (!scanner.hasNextInt()) {
if (scanner.hasNextLine()) {
scanner.nextLine(); // we've got something but it's not a number, discard it
}
}
int decimal = input.nextInt();
if (decimal > 0 && decimal <= 100) {
//code
}
else {
System.exit(0);
}
In this case the loop will continue until it finds an integer to read from the input, discarding lines of input if they don't start with an integer.
I just thought I would throw this in here since it is another flexible alternative to accomplishing the task. It utilizes the Scanner#nextLine() method with input validation to ensure that what is supplied is actually what is expected without the worry of an exception being thrown.
Validation is done using the String#matches() method supplied with a small Regular Expression (RegEx) to insist that numerical digits are supplied and that the supplied value is within the desired inclusive unsigned numerical range of 1 to 100. If the validation fails then the User is expected to try again or enter 'Q' (or anything that starts with Q - case insensitive) to quit.
Scanner input = new Scanner(System.in);
int intValue = 0;
String numberString = "";
// Prompt and Input...
while (intValue == 0) {
System.out.print("Enter a number (or 'q' to quit): --> ");
numberString = input.nextLine().toLowerCase();
//Quit..
if (numberString.charAt(0) == 'q') {
System.exit(0);
}
// Integer (unsigned - Range 1 to 100)...
else if (numberString.matches("100|[1-9][0-9]{1}?")) {
intValue = Integer.parseInt(numberString);
}
else {
System.err.println("Invalid numerical value supplied or the supplied");
System.err.println("value is not in the inclusive range of 1 to 100!");
System.err.println("Try Again...");
System.err.println();
}
}
//Your processing code here.
System.out.println("The value you entered is: --> " + intValue);
Explanation for the RegEx used within the String#matches() method:
100|[1-9][0-9]{1}?
1st Alternative 100
100 matches the characters 100 literally (case sensitive)
2nd Alternative [1-9][0-9]{1}?
Match a single character present in the list below [1-9]
1-9 a single character in the range between 1 (index 49) and 9 (index 57) (case sensitive)
Match a single character present in the list below [0-9]{1}?
{1}? Quantifier — Matches exactly one time (meaningless quantifier)
0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
If you want to change your numerical range then you may find this site useful.

Continue prompting till criteria fulfiled

I am practicing exception handling and have more or less grasp the basic concept.
I have been searching up on how to continue execution by prompting user to input the value which fulfills the specific criteria despite catching the exception by using a loop
I have this specific code that request user to enter a value between a range and have an exception handling to catch if a string is being input-ed. However, the program stops executing after it prints out the exception handling.
Any ideas how I can implement a loop or any other method that can continue the program execution after exception handling?
Scanner scanner = new Scanner(System.in);
int num = 0;
try
{
System.out.print("Please enter a number between 1 to 50 : ");
num = scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("Not a number");
return;
}
while (num > 50 || num < 1) {
System.out.print("Out of range. Enter a number between 1 to 50 : ");
num = scanner.nextInt();
}
System.out.println("The number is : " + num);
Exceptions should handle exceptional situations, i.e. situations you couldn't anticipate in advance. Since you can definitely anticipate that the user may enter invalid input, you can handle that invalid input without any exception handling :
Scanner scanner = new Scanner(System.in);
int num = 0;
while (num > 50 || num < 1) {
System.out.print("\nPlease enter a number between 1 to 50 : ");
while (!scanner.hasNextInt()) {
scanner.next(); // discard non-integer inputs
System.out.print("\nPlease enter a number between 1 to 50 : ");
}
num = scanner.nextInt();
}
System.out.println("You entered " + num);
Sample output :
Please enter a number between 1 to 50 : -1
Please enter a number between 1 to 50 : 53
Please enter a number between 1 to 50 : ff
Please enter a number between 1 to 50 : rr rr ff
Please enter a number between 1 to 50 :
Please enter a number between 1 to 50 :
Please enter a number between 1 to 50 : 13
You entered 13
Note that this code is much shorter than the version that uses exception handling.
Use this:
Scanner scanner = new Scanner(System.in);
boolean isInputValid = false; // input flag, valid = true / invalid = false
int num = 0;
while(!isInputValid) {
try
{
System.out.print("Please enter a number between 1 to 50 : ");
num = scanner.nextInt();
// Input is a valid integer
if (!(num > 0 && num < 51)) { // input out of range
System.out.print("Out of range.");
}
else
isInputValid = true; // input valid, proceed & break loop
}
catch (InputMismatchException ex) { // input not an integer
System.out.println("Not a number");
scanner.next();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
System.out.println("The number is : " + num);

How can you check user input validation in Java?

I'm making a simple program that asks the user to input five numbers between 0-19. I would like to add something (like an if statement) after every number to make sure it's within that range. If not, the program should say "please read instructions again" and will then System.exit(0). This is the piece of the code that is relevant:
System.out.println("Please enter 5 numbers between 0 and 19");
System.out.print("1st Number: ");
userNum1 = scan.nextInt();
System.out.print("2nd Number: ");
userNum2 = scan.nextInt();
System.out.print("3rd Number: ");
userNum3 = scan.nextInt();
System.out.print("4th Number: ");
userNum4 = scan.nextInt();
System.out.print("5th Number: ");
userNum5 = scan.nextInt();
Any help would be greatly appreciated.
You can put this after each of your inputs, but you might want to think about putting this logic into its own method, then you can reuse the code and just call it with something like validateInput(userNum1);.
Replace val with your actual variable names.
if (val < 0 || val > 19) {
System.out.println("please read the instructions again");
System.exit(0);
}
First of all, I would create a for-loop that iterates N times, with N being the number of numbers you want to ask for (in your case, 5). Imagine your example with 50 numbers; it would be very repetitive.
Then, when you get each number with scan.nextInt() within your for-loop, you can validate however you want:
if (userNum < 0 || userNum > 19) {
// print error message, and quit here
}
Also, instead of just exiting when they input a number outside the range, you could have your logic inside a while loop so that it re-prompts them for the numbers. This way the user doesn't have to restart the application. Something like:
boolean runApplication = true;
while(runApplication) {
// do your for-loop with user input scanning
}
Then set the runApplication flag as needed based on whether or not the user put in valid numbers.
This code will do the trick for you, i added some securities :
public static void main(String[] args) {
int count = 1;
Scanner scan = new Scanner(System.in);
List<Integer> myNumbers = new ArrayList<Integer>();
System.out.println("Please enter 5 numbers between 0 and 19");
do {
System.out.println("Enter Number "+count+" ");
if(scan.hasNextInt()){
int input = scan.nextInt();
if(input >= 0 && input <= 19){
myNumbers.add(input);
count++;
}else{
System.out.println("Please read instructions again");
System.exit(0);
}
}else{
scan.nextLine();
System.out.println("Enter a valid Integer value");
}
}while(count < 6);
/* NUMBERS */
System.out.println("\n/** MY NUMBERS **/\n");
for (Integer myNumber : myNumbers) {
System.out.println(myNumber);
}
}
Hope it helps
Since you already know how many numbers you want the user to input, I suggest you use a for loop. It makes your code more elegant and you can add as many more entries as you want by changing the end condition of the loop. The only reason it looks long is because number 1, 2, 3 all end in a different format i.e firST secoND thiRD, but the rest of the numbers all end with TH. This is why I had to implement some if else statements inside the loop.
To explain the code, every time it loops it first tells the user the count of the number he/she is entering. Then numEntry is updated every time the loop loops, therefore you do not need to assign multiple inputs to multiple variables. It is more efficient to update the same variable as you go on. If the input the user inputs is less than 0 OR it is more than 19, the system exits after an error message.
System.out.println("Please enter a number between 0 and 19");
Scanner scan = new Scanner(System.in);
for(int i = 1; i <=5; i++){
if(i == 1)
System.out.println("1st Number");
else if(i == 2)
System.out.println("2nd Number");
else if(i == 3)
System.out.println("3rd Number");
else
System.out.println(i + "th Number");
int numEntry = scan.nextInt();
if(numEntry < 0 || numEntry > 19){
System.out.println("Please read instructions again.");
System.exit(1);
}

Try-Catch inside a loop

In the below code, I ask the user to give an integer input and if the input is 0 or a negative number, it loops again until the positive number is given. The thing is that if the users presses a letter, my code crashes and despite the fact that I used try-catch in a lot of ways nothing really worked. Any ideas?
I used try-catch inside the loop, but it only worked for one letter input and not correctly.
System.out.print("Enter the number of people: ");
numberOfPeople = input.nextInt();
while (numberOfPeople <= 0) {
System.out.print("Wrong input! Enter the number of people again: ");
numberOfPeople = input.nextInt();
}
The problem in your current code is that you're always trying to read an int so when receiving a non-integer input you can't handle the error in the right way. Modify this to always read a String and convert it into an int:
int numberOfPeople = 0;
while (numberOfPeople <= 0) {
try {
System.out.print("Enter the number of people: ");
numberOfPeople = Integer.parseInt(input.nextLine());
} catch (Exception e) {
System.out.print("Wrong input!");
numberOfPeople = 0;
}
}
//continue with your life...

Categories

Resources