Try-Catch inside a loop - java

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...

Related

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.

hasNextInt() keeps waiting for input when pressing Enter

First post/question here and very new to java. Trying to make a small text based movie database app. One part of it is to add a review. The problem is when I just hit [enter] when asked for a Score number [0-10] on the review, the prompt just drops one step down and keeps waiting for input. I want it to be impossible to leave this field blank. Here is what I have so far:
int score;
do {
while (!sc.hasNextInt()) {
sc.next();
System.out.print("\nInvalid input! ");
System.out.print("Please enter a number from 0-10: ");
}
score = sc.nextInt();
if (!(score >= 0 && score <= 10)) {
System.out.print("\nInvalid input! ");
System.out.print("Please enter a number from 0-10: ");
}
} while (!(score >= 0 && score <= 10 ));
Scanner is reading tokens, i.e. text separated by whitespaces. That means, that as long as you just press Enter, the next token hasn't even started yet.
One of the fallacies of Scanner is that it's so easy to use, but even easier to misuse, e.g. mishandling user input.
Example: What should happen if used enters 123 abc<enter>? Your code will read 123 and continue, leaving abc in the buffer for the next prompt, which might want text and hence read the abc as that text. Oops!!
Most of the time, to handle bad user input, you should never use hasNextXxx() and nextXxx() methods other than nextLine(). It's the only way to ensure you get one answer (input) for one prompt.
So, you should do something like this:
int score;
for (;;) {
System.out.print("Please enter a number from 0-10: ");
String line = sc.nextLine();
try {
score = Integer.parseInt(line.trim());
} catch (NumberFormatException e) {
System.out.println("Invalid input! Not a number.");
continue;
}
if (score < 0 || score > 10) {
System.out.println("Invalid input! Out of range.");
continue;
}
break;
}

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);
}

How to repeat until the user enters an integer?

This is currently my code.
What I want it to do, is accept up to 10 numbers in an array then do and display some math for them. What I managed to do, is catch errors, then stop the program.
What I want it to do, is keep the program running until the user correctly enters an integer.
I managed to do something similar for my y/n string, but I don't know how to do it for integer arrays.
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int i=0, numberlist[] = new int [10];
String yn=null;
while (i < 10)
{
try {
System.out.print("Please enter your number\n");
numberlist[i]=input.nextInt();
System.out.print("Would you like to enter another number? (y/n)\n");
yn=input.next();
i++;
if (i==10)
{System.out.println("You reached the maximum amount of numbers\n");
break;}
if (yn.equals("n"))
break;
else if (!yn.equals("y"))
while (true)
{System.out.print("Please only enter a 'y' for yes or 'n' for no next time.\nDo you understand? Type 'y' to continue\n");
yn=input.next();
if (yn.equals("y"))
break;
}
}catch (Exception e){System.out.println("Please enter the correct number(integers only) next time.");}
}
int max=numberlist[0], min=numberlist[0], numlength = i, sum=0;
float average;
for(i = 0; i < numlength; i++) {
if(numberlist[i] > max)
max = numberlist[i];
}
for(i = 0; i < numlength; i++) {
if(numberlist[i] < min)
min = numberlist[i];
}
for(i = 0; i < numlength; i++) {
sum=numberlist[i]+sum;
}
average = (float)sum/(float)numlength;
System.out.println("Your Sum is: "+sum);
System.out.println("Your Average is: "+average);
System.out.println("Your Maximum is: "+max);
System.out.println("Your Minimum is: "+min);
}
Move your error handling for numbers inside the while loop so that any exceptions don't break the flow out of the loop and end the program.
while (i < 10) {
try {
System.out.print("Please enter your number\n");
numberlist[i] = input.nextInt();
System.out.print("Would you like to enter another number? (y/n)\n");
yn = input.next();
i++;
if (i == 10) {
System.out.println("You reached the maximum amount of numbers\n");
break;
}
if (yn.equals("n"))
break;
else if (!yn.equals("y"))
makeUserUnderstand(input,
"Please only enter a 'y' for yes or 'n' for no next time.");
} catch (InputMismatchException e) {
makeUserUnderstand(input,
"Please enter the correct number (integers only) next time.");
}
}
I've moved out the common "Do you understand?" part into a method.
private static void makeUserUnderstand(Scanner input, String msg) {
while (true) {
System.out.println(msg);
System.out.println("Do you understand? Type 'y' to continue\n");
if (input.next().equals("y"))
break;
}
}
First of all, don't catch Exception. You should catch only the specific exceptions that you care about and know might occur in your code. Any other exceptions indicate a serious problem and by catching them, you can accidentally squelch important information that indicates a bug that needs your attention.
With that said, you can solve your problem by making your try block smaller by only wrapping the code that reads input. In addition, create a loop that checks a flag that indicates if an error occurred. The flag can be set in the catch block when an error occurs parsing the input into an integer.
If you have trouble translating my description into code, feel free to ask about the details.

Set boundaries for integer input

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.
}

Categories

Resources