I was trying to write a program that prompts the user to read two integers and displays their sum and my program should prompt the user to read the number again if the input is incorrect. That's what I came up with:
import java.util.*;
public class NumFormatException {
public static void main(String[] args) throws NumberFormatException {
Scanner input=new Scanner(System.in);
System.out.println("Enter 2 integers: ");
int num1=0;
int num2=0;
boolean isValid = false;
while (!isValid) {
try
{
num1=input.nextInt();
num2=input.nextInt();
isValid=true;
}
catch(NumberFormatException ex)
{
System.out.println("Invalid input");
}
}
System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));
}
}
My main goal is to put the user in a situation to re-enter an integer if the input is incorrect. When I enter two integers, operation work well but my problem is with the exception: when I enter for example a instead of an integer, my program crashed.
There are two problems here. First, If a nextXYZ method of Scanner encounters a wrong input, it won't throw a NumberFormatException but an InputMismatchException. Second, if such an exception is thrown, the input token won't be consumed, so you need to consume it explicitly again:
try {
num1=input.nextInt();
num2=input.nextInt();
isValid=true;
} catch (InputMismatchException ex) { // catch the right exception
System.out.println("Invalid input");
// consume the previous, erroneous, input token(s)
input.nextLine();
}
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.
I wanted to print the multiplication table of a number. So I made a while(true) block to ontinously take inputs from the user. I also made a try and catch block, so that I could handle the exeptions.
Here is my code below :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Getting the multiplication table of any number");
while (true) {
try {
System.out.println();
System.out.print("Enter a number: ");
long number = scanner.nextLong();
for (byte num = 1; num < 11; num++) {
System.out.println(number + "X" + num + " = " + (number * num));
}
System.out.println();
System.out.println();
} catch (Exception e) {
System.out.println("Please enter a valid input.");
}
}
}
}
When I run the programm, it run fine till I introduce just one error. Then it just gives the output:
Enter a number: Please enter a valid input.
Both the statements on the same line, And just continuosly prints the line without any delay or without letting me give it an input.
Why is this happening and how can I correct it?
You can change your catch block as:
catch (Exception e) {
System.out.println("Please enter a valid input.");
scanner.next();
}
Professor requires us to write a program that will give the user prompt to enter two float (or double) values. If the values inputted are correct then display the inputted two values. If user enters characters instead of numbers or if they enter invalid numbers then the program will display the error message and ask the user to re-enter the correct values again. It only exits when the correct input is received and displayed.
However, I wrote a program that will only work if the user input the two right doubles. Can someone helps me to change the line about catching errors? Thanks.
import java.util.Scanner;
public class FiveSecond {
static void printMenu() {
System.out.println("Welcome to get two doubles program:");
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean valid = false;
double first = 0;
double second = 0;
printMenu();
while(!valid) {
System.out.print("Enter two doubles, seperate by space ");
try {
first = Double.parseDouble(scan.next());
second = Double.parseDouble(scan.next());
} catch (NumberFormatException e) {
System.out.println("Try again");
}
valid = true;
}
System.out.println("You entered valid choice: " + first + " " +second);
System.out.println("Thank you for giving your choice.");
scan.close();
}
}
Try this:
catch (NumberFormatException e) {
System.out.println("Try again");
continue;
}
In addition to the previous comments, you have to be careful, because the scanner will 'remember' a previously correct double if you don't reset it :
EDITED: Thanks to #Stultuske comment
while (!valid) {
System.out.print("Enter two doubles, seperate by space ");
try {
first = Double.parseDouble(scan.next());
second = Double.parseDouble(scan.next());
valid = true;
}
catch (NumberFormatException e) {
System.out.println("Try again");
scan.nextLine(); // <------- Important line
}
}
The following code will give me what I want which is the type of data entered (int, double, or string) however, when I run the code it is as if it expects another input before it will execute. I hope I'm on the right path.
or
Enter some stuff: 43
3
You have entered an integer: 43
It will not run until I enter another character in this case the 3 below 43.
Thanks for looking.
public static void main(String[] args)
{
// variables
Scanner in = new Scanner(System.in);
String input;
// Prompt user for stuff
System.out.print ("Enter some stuff: ");
// input stuff
input = in.next();
//determine and read type echo to use
if (in.hasNextInt())
{
System.out.print ("You have entered an integer: "+ input);
}
else if (in.hasNextDouble())
{
System.out.print ("You have entered a double: "+ input);
}
else if (in.hasNextLine())
{
System.out.print ("You have entered a string: "+ input);
}
}
I would use try and catch in order to found the right data type. Don't use multiple inputs otherwise you will get the error that you got, just use in.next() once and then handle the value as below:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input;
// Prompt user for stuff
System.out.print ("Enter some stuff: ");
// input stuff
input = in.next();
//determine and read type echo to use
try {
int v = Integer.parseInt(input);
System.out.print ("You have entered an integer: " + input);
} catch (NumberFormatException nfe1) {
try {
double v = Double.parseDouble(input);
System.out.print ("You have entered a double: " + input);
} catch (NumberFormatException nfe2) {
System.out.print ("You have entered a string: " + input);
}
}
}
Output 1:
Enter some stuff: 7
You have entered an integer: 7
Output 2:
Enter some stuff: 3.0
You have entered a double: 3.0
Output 3:
Enter some stuff: sfsdfasd
You have entered a string: sfsdfasd
I think you are doing it incorrectly. If you want to know the type of the data you entered, why would you read it first? You are first reading and storing it in input variable and determining the type of the next entered input. So, the message is also wrong. I've altered your code to get desired output
public static void main(String[] args) {
// variables
Scanner in = new Scanner(System.in);
String input;
// Prompt user for stuff
System.out.print ("Enter some stuff: ");
// input stuff
// input = in.next();
//determine and read type echo to use
if (in.hasNextInt())
{
System.out.println ("You have entered an integer: "+ in.nextInt());
}
else if (in.hasNextDouble())
{
System.out.println ("You have entered a double: "+ in.nextDouble());
}
else if (in.hasNextLine())
{
System.out.println ("You have entered a string: "+ in.nextLine());
}
}
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.