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);
Related
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");
}
I can't seem to understand how to use a while loop to determine whether a number is positive or not. While (I > 0), if I put any positive number, it will always result above 0 meaning there's an infinite loop.
int i = 0;
System.out.println("#1\n Input Validation\n Positive values only"); // #1 Input Validation
System.out.print(" Please enter a value: ");
Scanner scan = new Scanner(System.in);
i = scan.nextInt();
while (i > 0)
{
System.out.println("The value is: " +i);
}
System.out.println("Sorry. Only positive values.");
Also, when I input a negative number, it doesn't go back to the scanner to possibly input a positive number.
You can go to this kind of approach:
int i = 0;
System.out.println("#1\n Input Validation\n Positive values only"); // #1 Input Validation
Scanner scan = new Scanner(System.in);
while (i >= 0) {
System.out.print(" Please enter a value: ");
i = scan.nextInt();
if (i > 0) {
System.out.println("The value is: " + i);
} else {
break;
}
}
System.out.println("Sorry. Only positive values.");
I believe this is what you're trying to achieve.
int i = 0; // int is 0
while (i <= 0) {
// int is 0 or a negative number
System.out.println("#1\n Input Validation\n Positive values only");
System.out.print(" Please enter a value: ");
Scanner scan = new Scanner(System.in);
i = scan.nextInt();
if (i > 0) {
System.out.println("The value is: " + i);
} else {
System.out.println("Sorry. Only positive values.");
}
// if number is positive then continue to termination. If negative then repeat loop
}
Pay closer attention to where you place your while loop as your initial placement would certainly result in an infinite loop
while (i > 0)
{
System.out.println("The value is: " +i);
// number is positive - repeat loop containing only this line of code to infinity
}
// number is either 0 or negative so continue to termination
My task is to allow a user to input their lottery numbers and check if
they have won the jackpot.
The user should be given the chance to enter 4 numbers. Each number should be in the range 1-99. If
the user enters a number that is less than 1, or greater than 99, then the programme should prompt
them to enter a number in the correct range. You should use a while loop to ensure that the user inputs
the correct number. What should the exit condition of the while loop be?
I have tried making a while loop as the task asks me to do. this did not work. I am completely and utterly stuck.
String password = "MyNameJeff";
Scanner dave = new Scanner(System.in);
System.out.println("lottery numbers");
int UserInput = dave.nextLine();
while (!password.equals(UserInput)) {
System.out.println random math command <----
UserInput = dave.nextLine();
}
System.out.println("Lottery numbers here?");
This while loop will take the first userInput and check its range between 1 and 99 inclusive.
while(userInput < 1 || userInput > 99){
System.out.println("Please re-enter another lottery number: ");
userInput=dave.nextInt();
}
If it is not in the range 1 to 99, it will request the user to re-enter another lottery number.
the condition is when you want to stop the while loop. for example
you may want to stop when you have 4 numbers
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Scratch {
public static void main(String[] args) {
List<Integer> choices = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
boolean done = false;
//we set done to false, and the condition is "while !(not) done"
while (!done) {
try {
System.out.println("write lottery numbers:");
String userInput = scanner.nextLine();
Integer result = Integer.parseInt(userInput);
// compareTo is a bit tricky, read the javadoc for information
if (result.compareTo(0) < 0) {
System.out.println("dont add number less then 0");
continue;
}
if (result.compareTo(99) > 0) {
System.out.println("dont add number more then 99");
continue;
}
//adding more result is the only way done will be eventually true
choices.add(result);
//set to done when the size of the list is 4
done = choices.size() == 4;
} catch (NumberFormatException e) {
System.out.println("Only add number");
}
}
System.out.println("Lottery numbers here?");
choices.forEach(System.out::println);
}
}
Check this code
public static void main (String[]args) throws IOException, ParseException {
int [] winNumbers = new int[4];
int [] numbers = new int[4];
int indx=0;
System.out.println("Enter Lottery Numbers");
while (indx<4) {
System.out.println("Enter number: ");
Scanner dave = new Scanner(System.in);
try {
String in = dave.nextLine().trim();
int inNum = Integer.parseInt(in);
if (inNum>0 && inNum<100) {
numbers[indx] = inNum;
indx++;
continue;
}
}
catch (NumberFormatException | NullPointerException nfe) {
}
System.out.println("Please enter a number in the range 1-99");
}
Random rand = new Random();
for (int i=0; i<winNumbers.length; i++){
int r = rand.nextInt(98);//will get a random number between 0-98
r +=1; // for the number to be on the space 1-99
winNumbers[i]=r;
}
System.out.println("User entered: " + Arrays.toString(numbers));
System.out.println("Lottery numbers here: " + Arrays.toString(winNumbers));
}
Two int arrays are used with size 4.
One is filled using Scanner. There are some checks:
trim(): will remove any whitespace that the user might enter
catch: will catch a numberFormatException or null. It will print nothing.
If the code does not enter the if(inNum>0 && inNum<100) then the indx counter will not increment and the code will print the error message: Please enter a number...
The second part of the code generates 4 random numbers and stores them in the second array.
Finally, it prints the two arrays.
I was wondering how you can the scanner can pick up all the different numbers on the same line. my assignment has requires us to compute grade averages and he wants it to be like:
Enter the number of grades: 5
Enter 5 grades: 95.6 98.25 89.5 90.75 91.56
The average of the grades is 93.13
I think for the scanner to get those number it requires an array? but we haven't learned those. Any help would be awesome! So far I have:
// number of grades input
do {
System.out.println("Enter number of grades");
// read user input and assign it to variable
if (input.hasNextInt()) {
numGrade = input.nextInt();
// if user enters a negative grade will loop again
if (numGrade <= 0) {
System.out.println("Your number of grades needs to positive! Try again");
continue;
// if grade number > 0 set loop to false and continue
} else {
cont = false;
}
// if user does not enter a number will loop again
} else {
System.out.println("You did not enter a number! Try again");
// get the next input
input.next();
continue;
}
// only not loop when boolean is false
} while (cont);
// user input of grades
do {
// prompt user to enter the grades
System.out.println("Enter the " + numGrade + " grades");
// assign to input
if (input.hasNextDouble()) {
grades = input.nextDouble();
// check if a grade is a negative number
if (grades <= 0) {
// report error to user and loop
System.out.println("Your grades needs to positive! Try again");
continue;
// if user enter acceptable grades then break loop
} else {
cont2 = false;
}
// check if user entered a number
} else {
// if user did not enter number report error
System.out.println("You did not enter a number! Try again");
input.next();
continue;
}
// only not loop when boolean2 is false
} while (cont2);
// average calculation
average = grades / numGrade;
System.out.println(average);
}
I would suggest this
// separates the line you send by spaces if you send the next line
// 95.6 98.25 89.5 90.75 91.56 it will create an array like this
// {"95.6","98.25", "89.5","90.75", "91.56"}
String []grades = input.nextLine().split(' ');
double total=0;
for(int i=0;i<grades.length;i++){
//parse each value to double and adds it to total
total+=Double.parseDouble(grades[i]);
}
double average= total/grades.length;
I think in your assignment the separate spaces means that you should have each number stored in a specific location or variable.
For example:
Enter three number : 1 2 3
int number1 = input.nextInt();
int number2 = input.nextInt();
int number3 = input.nextInt();
now Scanner will read by nextInt() method. if it read space then will finished saving value in that variable.
Another Example that read array elements:
Enter three number: 1 2 3
int[] myArray = new int[3];
for(int i = 0; i < myArray.length; i++){
myArray[i] = input.nextInt();
}
Note that the loop will run 3 times as the length of the array.
Also note in the code that input reference for Scanner class but I didn't declare it.
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.
}