I want the program to not crash when the user inputs anything other than a number. For example, if someone enters random letters, it should display a message saying, "input not valid, please enter a valid integer". Then prompting them if they would want to continue or not.
public static void main(String[] args) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter("outDataFile.txt"));
Scanner input=new Scanner(System.in);
int choice = 0;
String repeat;
//Loop repeats program until user quits
do
{
//Loop repeats until a valid input is found
do
{
//Asks for number and reads value
System.out.print("\nEnter an integer and press <Enter> ");
choice = input.nextInt();
//Prints error if invalid number
if(choice <= 0)
System.out.println("Invalid Input.");
There are multiple ways to achieve that:
First is to catch the exception thrown by the Scanner and flag the loop to carry on when an exception is caught. This is not a good practise since the exception thrown by the Scanner, InputMismatchException, is an unchecked exception. Meaning the cause of this exception can be easily caught by an if/else statement.
In your case, you should try to receive the input as a String, then validate the input if it looks like a number:
Loop per character approach:
String string = scanner.nextLine();
for (int i = 0; i < string; i++) {
char ch = string.charAt(i);
if (!Character.isDigit(ch)) {
System.out.println("Input is not a number");
break; // stop the for-loop
}
}
int input = Integer.parseInt(string);
RegEx approach:
String numericRegex = "[0-9]+";
String string = scanner.nextLine();
if (!string.matches(numericRegex)) {
System.out.println("Input is not a number");
}
int input = Integer.parseInt(string);
These are popular approach to your problem, it is now up to you on how will you control your loops to repeat when an invalid input is encountered.
Use a simple try catch that will catch and a simple recursive method as such:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
System.out.println(getUserInput());
}
private static int getUserInput()
{
int choice = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter a value");
try
{
choice = input.nextInt();
} catch (InputMismatchException exception)
{
System.out.println("Invalid input. Please enter a numeric value");
getUserInput();
}
return choice;
}
}
Related
I'm confused while using an Java program I created.
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
int input1 = 0;
boolean Input1Real = false;
System.out.print("Your first input integer? ");
while (!Input1Real) {
String line = scanner1.nextLine();
try {
input1 = Integer.parseInt(line);
Input1Real = true;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.print("Your first input integer? ");
}
}
System.out.println("Your first input is " + input1);
}
Initially, when a user Ctrl+D during the input, it will promptly end the program and display an error in the form of this,
Your first input integer? ^D
Class transformation time: 0.0073103s for 244 classes or 2.9960245901639343E-5s per class
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651);
at Playground.Test1.main(Test1.java:13)
Doing a bit of research I note that Ctrl+D terminates the input of sort. Therefore, I tried add few more lines to my codes to prevent the error from appearing again and instead printing a simple "Console has been terminated successfully!" and as far as my skills can go.
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
int input1 = 0;
boolean Input1Real = false;
System.out.print("Your first input integer? ");
while (!Input1Real) {
String line = scanner1.nextLine();
try {
try {
input1 = Integer.parseInt(line);
Input1Real = true;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.print("Your first input integer? ");
}
}
catch (NoSuchElementException e) {
System.out.println("Console has been terminated successfully!");
}
}
System.out.println("Your first input is " + input1);
}
In the end, I still got the same error.
Got it!, the code hasNext() will ensure that the error will not appear. This method is to check whether there is another line in the input of the scanner and to check if its filled or empty. I am also using null to check my statement after passing the loop so the program stops if the input value is still null while keeping the function of Ctrl+D.
public static void main(String[] args) {
Integer input1 = null;
System.out.println("Your first input integer? ");
Scanner scanner1 = new Scanner(System.in);
while(scanner1.hasNextLine()) {
String line = scanner1.nextLine();
try {
input1 = Integer.parseInt(line);
break;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.println("Your first input integer? ");
}
}
if (input1 == null) {
System.out.println("Console has been terminated successfully!");
System.exit(0);
}
System.out.println(input1);
}
This solution is not prefect of course but I would appreciate if there were much simpler options.
Currently I have a code that looks like this
import java.util.*;
public class Main
{
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String[] status={"f","f","f","f"};
System.out.println("Enter index to change: ");
int userInput = input.nextInt();
status[verify(status,userInput)] = "changed";
System.out.println(Arrays.toString(status));
}
private static int verify(String statusList[],int userIndex){
while(userIndex > (statusList.length-1) || userIndex < 0){
System.out.println("Invalid Index,enter correct Index ");
userIndex = input.nextInt();
}
return userIndex;
}
}
The "verify" method is used to check whether the user enters an index which is out of Bounds.
I am wanting to extend the "verify" method to check if the user enters a string but am not sure how to do that. I want a message to be displayed saying that the user has entered a string and want to keep getting the user input until a correct array index is entered.
Is there any way to check whether a string is entered, in the same method?
Actually, nextInt method on Scanner class will throw you an InputMismatchException if the user inputs something that's not Integer. Take a look at nextInt method signature. If you want, you can catch that exception and log message that you want into the console.
Take a look at the following code. Hope it works for you.
Java
import java.util.Arrays;
import java.util.Scanner;
public class Scan {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String[] status={"f","f","f","f"};
System.out.println("Enter index to change: ");
int userInput = verify(status, input);
status[userInput] = "changed";
System.out.println(Arrays.toString(status));
}
private static int verify(String statusList[], Scanner input){
do {
int userIndex=-1;
String line = input.next();
try {
userIndex = Integer.parseInt(line);
}catch(NumberFormatException e) {
System.out.println("Please enter a number.");
continue;
}
if(userIndex > (statusList.length-1) || userIndex < 0){
System.out.println("Invalid Index,enter correct Index ");
continue;
}else {
return userIndex;
}
}while(true);
}
}
so I'm kind of new to catching errors and such. Anyways, the program is supposed to ask the user for 2 integers and then add them together. Simple, but if either of the numbers are not integers, than an error is thrown. Currently, if I enter 2 integers, instead of adding them, it just restarts the getAnswer() method and outputs them again. Also, if you enter more than one error, it will simply exit.
package javaapplication1;
import java.util.InputMismatchException;
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
Intro();
System.out.println("Your answer: "+getAnswer());
}
private static void Intro() {
System.out.println("Hello this program adds 2 integers together and catches errors.");
getAnswer();
}
private static int getAnswer() throws InputMismatchException {
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Please input a number");
int num1 = scanner.nextInt();
System.out.println("Please input a second number");
int num2 = scanner.nextInt();
return num1+ num2;
} catch (InputMismatchException exp) {
System.out.println("Exception thrown");
return 0;
}
}
}
You are calling getAnswer(); totally two times, so you just remove the call from Intro() method which will solve the problem.
private static void Intro() {
System.out.println("Hello this program adds 2
integers together and catches errors.");
}
If you want to prompt the user to reenter the input again, you can call the getAnswer() in the catch block as shown below:
private static int getAnswer() {
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Please input a number");
int num1 = scanner.nextInt();
System.out.println("Please input a second number");
int num2 = scanner.nextInt();
return num1+ num2;
} catch (InputMismatchException exp) {
System.out.println("Exception thrown, please reenter values:");
getAnswer();
}
return 0;
}
One more point is that rather than catching the InputMismatchException, the other better way is read the inputs as strings and validate that they contain only numeric values like below:
private static int getAnswer() {
Scanner scanner = new Scanner(System.in);
System.out.println("Please input a number");
String num1 = scanner.nextLine();
System.out.println("Please input a second number");
String num2 = scanner.nextLine();
if(num1.matches("[0-9]+") && num2.matches("[0-9]+")) {
return Integer.parseInt(num1)+ Integer.parseInt(num2);
} else {
System.out.println(" Your inputs contain Invalid characters");
getAnswer();
}
return 0;
}
I am having trouble with entering non-integers into an integer field. I am only taking precautions so that if another person uses/works on my program they don't get this InputMismatchException.
When I enter a non-digit character into the input variable, I get the above error. Is there any way to compensate for this like one could do for a NullPointerException when it comes to strings?
This code is redacted just to include the relevant portions causing the problem.
import java.util.Scanner;
class MyWorld {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int input = 0;
System.out.println("What is your age? : ");
input = user_input.nextInt();
System.out.println("You are: " +input+ " years old");
}
}
You can use an if statement to check if user_input hasNextInt(). If the input is an integer, then set input equal to user_input.nextInt(). Otherwise, display a message stating that the input is invalid. This should prevent exceptions.
System.out.println("What is your age? : ");
if(user_input.hasNextInt()) {
input = user_input.nextInt();
}
else {
System.out.println("That is not an integer.");
}
Here is some more information about hasNextInt() from Javadocs.
On a side note, variable names in Java should follow the lowerMixedCase convention. For example, user_input should be changed to userInput.
You can add a try-catch block:
import java.util.Scanner;
class MyWorld {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int input = 0;
System.out.println("What is your age? : ");
try{
input = user_input.nextInt();
}catch(InputMisMatchException ex)
System.out.println("An error ocurred");
}
System.out.println("You are: " +input+ " years old");
}
}
If you want to provide the user to enter another int you can create a boolean variable and make a do-while loop to repeat it. As follows:
boolean end = false;
//code
do
{
try{
input = user_input.nextInt();
end = true;
}catch(InputMisMatchException ex)
System.out.println("An error ocurred");
end = false;
System.out.println("Try again");
input.nextLine();
}
}while(end == false);
This is a try-catch block. You need to use this if you want to be sure of not making the program-flow stop.
try {
input = user_input.nextInt();
}
catch (InputMismatchException exception) { //here you can catch that exception, so program will not stop
System.out.println("Integers only, please."); //this is a comment
scanner.nextLine(); //gives a possibility to try giving an input again
}
Test using hasNextInt().
Scanner user_input = new Scanner(System.in);
System.out.println("What is your age?");
if (user_input.hasNextInt()) {
int input = user_input.nextInt();
System.out.println("You are " + input + " years old");
} else {
System.out.println("You are a baby");
}
Use Scanner's next() method to get data instead of using nextInt(). Then parse it to integer using int input = Integer.parseInt(inputString);
parseInt() method throws NumberFormatException if it is not int, which you can handle accordingly.
There are several questions I would like to ask, please refer the comment part I have added in the code, Thanks.
package test;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
/* Task:
prompt user to read two integers and display the sum. prompt user to read the number again if the input is incorrect */
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean accept_a = false;
boolean accept_b = false;
int a;
int b;
while (accept_a == false) {
try {
System.out.print("Input A: ");
a = input.nextInt(); /* 1. Let's enter "abc" to trigger the exception handling part first*/
accept_a = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.nextLine(); /* 2. I am still not familiar with nextLine() parameter after reading the java manual, would you mind to explain more? All I want to do is "Clear Scanner Buffer" so it wont loop for the println and ask user to input A again, is it a correct way to do it? */
}
}
while (accept_b == false) {
try {
System.out.print("Input B: ");
b = input.nextInt();
accept_b = true;
} catch (InputMismatchException ex) { /*3. Since this is similar to the above situation, is it possible to reuse the try-catch block to handling b (or even more input like c d e...) exception? */
System.out.println("Input is Wrong");
input.nextLine();
}
}
System.out.println("The sum is " + (a + b)); /* 4. Why a & b is not found?*/
}
}
I am still not familiar with nextLine() parameter after reading the java manual, would you mind to explain more? All I want to do is "Clear Scanner Buffer" so it wont loop for the println and ask user to input A again, is it a correct way to do it?
The use of input.nextLine(); after input.nextInt(); is to clear the remaining content from the input stream, as (at least) the new line character is still in the buffer, leaving the contents in the buffer will cause input.nextInt(); to continue throwing an Exception if it's no cleared first
Since this is similar to the above situation, is it possible to reuse the try-catch block to handling b (or even more input like c d e...) exception?
You could, but what happens if input b is wrong? Do you ask the user to re-enter input a? What happens if you have 100 inputs and they get the last one wrong?You'd actually be better off writing a method which did this for, that is, one which prompted the user for a value and returned that value
For example...
public int promptForIntValue(String prompt) {
int value = -1;
boolean accepted = false;
do {
try {
System.out.print(prompt);
value = input.nextInt();
accepted = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.nextLine();
}
} while (!accepted);
return value;
}
Why a & b is not found?
Because they've not been initialised and the compiler can not be sure that they have a valid value...
Try changing it something more like.
int a = 0;
int b = 0;
Yes, it's okay. And will consume the non-integer input.
Yes. If we extract it to a method.
Because the compiler believes they might not be initialized.
Let's simplify and extract a method,
private static int readInt(String name, Scanner input) {
while (true) {
try {
System.out.printf("Input %s: ", name);
return input.nextInt();
} catch (InputMismatchException ex) {
System.out.printf("Input %s is Wrong%n", input.nextLine());
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = readInt("A", input);
int b = readInt("B", input);
System.out.println("The sum is " + (a + b));
}
I have put comment to that question line.
package test;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean accept_a = false;
boolean accept_b = false;
int a=0;
int b=0;
System.out.print("Input A: ");
while (accept_a == false) {
try {
a = input.nextInt(); // it looks for integer token otherwise exception
accept_a = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.next(); // Move to next other wise exception // you can use hasNextInt()
}
}
System.out.print("Input B: ");
while (accept_b == false) {
try {
b = input.nextInt();
accept_b = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.next();
}
}
System.out.println("The sum is " + (a + b)); // complier doesn't know wheather they have initialised or not because of try-catch blocks. so explicitly initialised them.
}
}
Check out this "nextLine() after nextInt()"
and initialize the variable a and b to zero
nextInt() method does not read the last newline character.