Asking for input after catching an exception - java

I want the user to enter a number which is scanned by the following code:
scanner.nextInt();
If a user enters a string instead, the program throws InputMismatchException, which is obvious. I want to catch the exception in such a way that the program prompts the user to enter an input until the user enters an integer value.
Scanner scanner = new Scanner(System.in);
while(true) {
try {
System.out.println("Please enter a number: ");
int input = scanner.nextInt();
System.out.println(input);
//statements
break;
}
catch(InputMismatchException | NumberFormatException ex ) {
continue;
}
}
This code creates an infinite loop if a string is entered.

The answer to my problem is as follows:
Scanner scanner = new Scanner(System.in);
while(true) {
try {
System.out.println("Please enter a number: ");
int input = scanner.nextInt();
System.out.println(input);
//statements
break;
}
catch(InputMismatchException | NumberFormatException ex ) {
scanner.next();//new piece of code which parses the wrong input and clears the //scanner for new input
continue;
}
}

Put Scanner scanner = new Scanner(System.in); within your while loop.
Scanner scanner;
while(true) {
try {
System.out.println("Please enter a number: ");
scanner = new Scanner(System.in);
int input = scanner.nextInt();
System.out.println(input);
//statements
break;
}
catch(InputMismatchException | NumberFormatException ex ) {
System.out.println("I said a number...");
}
}

How about this?
while(true) {
try {
System.out.println("Please enter a number: ");
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
System.out.println("\n\nEntered number is : " + input);
break;
} catch(InputMismatchException | NumberFormatException ex ) {
System.out.println("\n\nInput was not a number. Please enter number again : ");
} catch(Exception e ) {
System.out.println("\n\nException caught :: " + e);
}
}
I have also removed continue syntax as those are not needed.

Related

The scanner in my program is asking the user for second input, why is the scanner doing so?

I do not understand the reason why the method below is asking me for a second input when i type an integer as an input. Note, as far as i know, the method works fine when the input is a non integer, however when the user types an integer, then the method askes the user for a second input.
The method is:
public void setNumOfStudents() {
while (true) {
try {
System.out.print("Number of students: ");
String number = scanner.nextLine();
if (number.isEmpty()) {
while (number.isEmpty()) {
System.out.println("Please enter a valid number.");
System.out.print("Number of students: ");
number = scanner.nextLine();
}
}
numOfStudents = Integer.parseInt(number);
listOfStudents = new String[numOfStudents];
break;
}
catch (InputMismatchException | NumberFormatException e) {
System.out.println("Please enter an integer.");
continue;
}
}
}

Display an Error for invalid input in JAVA

I have written a JAVA program that takes input from the user and check if the user has entered the correct thing or not. I have taken the input from the Scanner class. If the user enters an invalid character like a String, I want to display 'Invalid Input'.
public class Main {
public static void main(String[] args) {
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
int enteredNumber = takeInteger.nextInt();
}
}
Just ask the Scanner whether the next input is a valid int value, e.g.
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
while(!takeInteger.hasNextInt()) {
System.out.println("Invalid Input: " + takeInteger.next());
}
int enteredNumber = takeInteger.nextInt();
This will retry the operation until the user entered a number. If you just want a single attempt, use something like
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
if(!takeInteger.hasNextInt()) {
System.out.println("Invalid Input: " + takeInteger.next());
}
else {
int enteredNumber = takeInteger.nextInt();
// ... proceed with the input
}
You will get an Exception that is InputMismatchException when an invalid input is passed.(i.e except integer value),you can use a try-catch block to hold the exception and inform the user about the invalid input. Try block , Catch block
import java.util.*;
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
try{
int enteredNumber = takeInteger.nextInt();
}
catch(InputMismatchException e) {
System.out.println("Enter a valid input");
}
You can use Exception handling for the same.
public class Main {
public static void main(String[] args) {
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
try {
int enteredNumber = takeInteger.nextInt();
}
catch (Exception e) {
System.out.println("Invalid Input");
}
}
}
You can add a try-catch block in your program to check if the user's input is a number or not.
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
String input = takeInteger.next();
int enteredNumber;
try
{
enteredNumber = Integer.parseInt(input); // Input is a number
}
catch(NumberFormatException ex)
{
System.out.println("Wrong Input!"); // Invalid input
}
You need to call the .nextLine method of the Scanner class and then parse to the desired type.
Example:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
String line = sc.nextLine();
try {
int enteredNumber = Integer.parseInt(line);
System.out.println("You have entered: " + enteredNumber);
} catch (Exception e) {
System.out.println("Invalid Input");
}
}
}
Result with a number:
Enter a number
12
You have entered: 12
Result a text:
Enter a number
abcd
Invalid Input

Repeatedly Ask user for input, if input is not an integer [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 1 year ago.
As the title says, i'm attempting to make my program re-ask for user input if the given input is invalid (In this case, invalid input is any input that is not an integer)
I've already tried this, but it does not work:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please input your age");
if (scanner.hasNextInt()) {
int age = scanner.nextInt();
System.out.println("Your age is: " + age);
System.out.println();
} else {
System.out.println("This input is not an integer - Please try again!");
int age = scanner.nextInt();
System.out.println("Your age is: " + age);
System.out.println();
}
}
}
I'm aiming for this to be done with while loop and scanner
My current code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please input your age");
if (scanner.hasNextInt()) {
int age = scanner.nextInt();
System.out.println("Your age is: " + age);
}
}
}
Any reply on this post is greatly appreciated.
You can use while-loop:
Scanner scanner = new Scanner(System.in);
boolean ageGiven = false;
while (!ageGiven) {
System.out.println("Please input your age");
String next = scanner.next();
try {
int age = Integer.parseInt(next);
System.out.println("Your age is: " + age);
ageGiven = true;
} catch (NumberFormatException e) {
System.out.println("This input is not an integer - Please try again!");
}
}
I think you should put while instead of if statement. Break after having correct input. Try out once.
As you suggested, a while loop is more appropriate to this.
Something like this should work:
Scanner scanner = new Scanner(System.in);
System.out.println("Please input your age");
boolean isValid = false;
int age;
while (!isValid) {
if (scanner.hasNextInt()) {
age = scanner.nextInt();
isValid = true;
}
else {
System.out.println("Invalid input. Please type a number");
}
}
System.out.println("Your age is: " + age);
In this case, it would loop while the IsValid boolean is false. And that variable would be set to true, once the user inputs a valid age.
Edit: Changed the code to check if the input is an integer.

Java Do While Validation

How do I change this while(true) into a do while so when the user enters a number they will be given back details but if they enter * the system will close.
while (true){
System.out.print("Enter number: ");
int option = keyboard.nextInt();
out.writeInt(option);
char option;
do {
System.out.print("Enter number: ");
option = keyboard.nextChar();
out.writeChar(option);
} while (option != '*')
You may want to use nextLine() or next() to receive the input and parse them accordingly:
do{
System.out.print("Enter number: ");
String str = keyboard.nextLine();
int option = 0;
if(str.matches"[0-9]+"){
option = Integer.parseInt(str);
System.out.println(option);
}
else if(str.equals("*"))
System.exit(0); //or use break; if you want to exit the loop
}while(whatever); //whatever == true
If you change it to allow the user to input a String and then convert to int if possible, you can catch any errors and break out if the user enters a '*' character:
import java.util.*;
class MainInput{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int option;
String input;
do{
System.out.print("Enter number: ");
input = keyboard.nextLine();
try{
option = Integer.parseInt(input);
System.out.println("You entered the value: " + option);
}
catch(Exception ex) {
if (!input.equals("*")){
System.err.println("Invalid input, please enter numbers only.");
}
}
}while(!input.equals("*"));
}
}
If you use an exit value like (-1), you can continue to process input with nextInt() and becomes even easier. You can do this with a simple do/while:
import java.util.*;
class MainInput{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int option = 0;
do{
System.out.print("Enter number: ");
option = keyboard.nextInt();
System.out.println("You entered the value: " + option);
}while(option != -1);
}
}
do{
System.out.print("Enter number: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
}while(!str.equals("*"))
edit: if you want to play with numbers as integer or double. Just let me know and I'll add casted version as your needs.
int number;
do{
System.out.print("Enter number: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
number = Integer.parseInt(str);
}while(!str.equals("*"))
now you have a integer number.

How to avoid stack build up?

I'm trying to figure out how I can write this method to avoid the stack buildup from recursively calling the method in the exception?
Here is the wording of my instructions:
Read a number, use an exception handler to make sure it is an int number and then add to the ArrayList object, aryList.
Here is my attempt:
public void createOriginalAryList() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a number: ");
try {
int number = keyboard.nextInt();
aryList.add(number);
while(keyboard.hasNextInt()) {
System.out.println("Enter a number: ");
number = keyboard.nextInt();
aryList.add(number);
}
} catch(InputMismatchException ime) {
System.out.println("Invalid number submitted! Try again.");
createOriginalAryList();
}
System.out.println(aryList);
}
Any suggestions are greatly appreciated!
Simply use a do-while loop:
Scanner keyboard = new Scanner(System.in);
boolean redo = false;
do {
System.out.println("Enter a number: ");
redo = false;
try {
int number = keyboard.nextInt();
aryList.add(number);
while(keyboard.hasNextInt()) {
System.out.println("Enter a number: ");
number = keyboard.nextInt();
aryList.add(number);
}
} catch(InputMismatchException ime) {
redo = true;
System.out.println("Invalid number submitted! Try again.");
}
}
while(redo);
System.out.println(aryList);
Since initializing the Scanner keyboard each time is useless, it is put before the loop.

Categories