Java validation error from user input - java

I have the following code, where the idea is that the user will input two numbers and the sum of the two will be calculated.
If an invalid value, e.g. a character is entered, an error message should be outputted but I keep getting errors
Java
package calculator;
import java.util.Scanner;
public class calculator {
/**
* #param args
*/
public static void main(String[] args) {
double n1, n2;
String operation;
Scanner scannerObject = new Scanner(System.in);
System.out.println("Enter first number");
n1 = scannerObject. nextDouble();
System.out.println("Enter second number");
n2 = scannerObject. nextDouble();
Scanner op = new Scanner(System.in);
System.out.println("Enter your operation");
operation = op.next();
switch (operation) {
case "+":
System.out.println("Your answer is " + (n1 + n2));
break;
case "-":
System.out.println("Your answer is " + (n1 - n2));
break;
case "/":
System.out.println("Your answer is " + (n1 / n2));
break;
case "*":
System.out.println("Your asnwer is " + (n1 * n2));
break;
default:
System.out.println("I do not know!");}
}
int function(){
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer between 1-100: ");
int range;
while(true){
if(input.hasNextInt()){
range = input.nextInt();
if(0<=range && range <= 100)
break;
else
continue;
}
input.nextLine(); //Comsume the garbage value
System.out.println("Enter an integer between 1-100:");
}
return range;
}
}
and these are the error messages I get:
Errors
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at calculator.calculator.main(calculator.java:14)
I've tried so many different things but can't get it to work as I want it.
Can anyone be of any assistance here?
Thanks for reading

This exception is thrown by an instance of the Scanner class to indicate that a retrieved token does not match the pattern for the expected type, or that the retrieved token is out of range.
You can see the documentation for the exception here: https://docs.oracle.com/javase/7/docs/api/java/util/InputMismatchException.html
Taken from documention on Scanner
double nextDouble()
Returns the next token as a long. If the next token is not a float or
is out of range, InputMismatchException is thrown.
I suspect that your not inputting your number correctly. Ensure that your input is of the correct format.
You should also set the locale of your scanner as some locales expect a comma , instead of a dot ., such as:
Scanner scanner = new Scanner(System.in).useLocale(Locale.US);

Your first two inputs should be numbers. If this is true, then it's probably the decimal mark for your numbers. You need a dot(.) not a comma (,)

It seems that you are not entering any integer as input.
You can solve this by handling the exception this way :
try {
if(input.hasNextInt()){
range = input.nextInt();
if(0<=range && range <= 100)
break;
else
continue;
}
input.nextLine();
}
catch (InputMismatchException e) {
input.nextLine();
}

Your issue is at,
scannerObject. nextDouble();
You are trying to get a double but entering a string. You will need to do some sort of a input validation like below to stop program from crashing incase of invalid inputs.
try {
System.out.println("Enter first number");
n1 = scannerObject. nextDouble();
}
catch(InputMismatchException inEx) {
System.out.println("Invalid input");
}
Then you may want to create a loop to get the input again and agin until valid input is detected.
Edit
You'll need to,
import java.util.InputMismatchException;
Also create a loop to get a valid input from a user. Something like below. This is just an example, you'll need to do something like this to work with your code. Also need to make sure n1 and n2 are initiated before you actually use their values.
boolean notValidInput = true;
while(notValidInput) {
try {
System.out.println("Enter first number");
n1 = scannerObject. nextDouble();
notValidInput = false;
}
catch(InputMismatchException inEx) {
System.out.println("Invalid input. Please try again!");
}
}

Related

How to loop wrong data type inputs? [duplicate]

This question already has an answer here:
While loop to determine if entered value is a double
(1 answer)
Closed 1 year ago.
I know there are lots of questions similar to this but I can't understand most of it, also I can't see any similar questions related to java language.
So can you guys help me how to loop this question if the input is not a double data type?
The code:
System.out.println("Enter first number");
num1 = input.nextDouble();
System.out.println("Enter second number");
num2 = input.nextDouble();
I really appreciate anyone who tries to answer, tia!!
This is a solution (without exception handling). It loops until two Doubles have been entered. So it is possible to enter this:
3
4.2
or also:
www
3
abc
4.2
Both will give the same result
3
4.2
Note that the code is locale sensitive in regard of the numbers you enter at the command prompt (meaning that the decimal sign depends on your computer settings – in Germany for example it is the comma and not the dot, so you would enter 4,2):
Scanner scanner = new Scanner(System.in);
Double part1 = null;
Double part2 = null;
while (true) {
if (scanner.hasNextDouble()) {
if (part1 == null ) {
part1 = scanner.nextDouble();
} else {
part2 = scanner.nextDouble();
break;
}
} else {
scanner.next(); // The input is not a Double, so just drop it
}
}
scanner.close();
System.out.println(part1);
System.out.println(part2);
If you add the line scanner.useLocale(Locale.ROOT) after creating the scanner:
Scanner scanner = new Scanner(System.in);
scanner.useLocale(Locale.ROOT);
the decimal sign will be the dot '.' like in 4.2 independent of the settings of your computer.
I like to create a separate method to validate input. If the value is invalid, then I have the method return -1. Then I'll have a while loop that checks if the input is -1, if so, than it'll ask the for a new input value till it's correct. There are many ways to go about it. But the gist is something like this.
public static void main(String[] Args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter first number");
double num1 = validateDouble(input);
while (num1 == -1) {
num1 = validateDouble(input);
}
System.out.println(num1);
}
private static double validateDouble(Scanner scanner) {
String input = scanner.nextLine();
try {
double i = Double.parseDouble(input);;
return i;
}catch (InputMismatchException | NumberFormatException e) {
if (input.equals("q")) {
System.exit(0);
}
System.out.println("Please try again.");
return -1;
}
}

How to fix loop while/try catch error in java

I am working on creating a simple calculator program (first week into this java programming).
problem background: only 5 options are valid. (1-add; 2- subtract; 3- multiple;4. divide; and 5.exit). when users enter 1-4 options, results will populate but users need to loop back to reenter data till option 5 is selected. 5 is to exit the program(the only way to end the loop/program). my questions: 1. how to stop try-catch from running nonstop? is there a better way to implement try-catch? e.g., handling string data error messages.Ideally, if a string is entered, the code should loop back to restart again by producing the message "please reenter the number..." until a valid number is entered by users 2. I am trying to use as many static methods as possible in the main class. i am not sure whether the way I did was accurate?
Here is the code I input:
12 2
//-everything works well.
2 //-enter again
s s (string entry-error)
then, the below message populates:
"You have entered invalid floats. please re-enter:
Exception in thread "main" java.util.InputMismatchException
...
at calculator.performSubtract(calculator.java:65)
at calculator.main(calculator.java:34)"
code(sample)
public class calculator {
//use static methods to implement the program
static Scanner userInput = new Scanner(System.in);
static int userChoice;
static float numberOne;
static float numberTwo;
static float answer;
static int choice;
public static void main(String[] args) {
do {
//this menu statement has to be repeated unless 5 is entered (exit the
//program)
System.out.println("Welcome to <dj's> Handy Calculator\n\n\t \1. Addition \n\t 2. Subtraction\n\t 3. Multiplication\n\t 4. Division\n\t 5. Exit\n\n");
System.out.print("What would you like to do? ");
try {
choice = userInput.nextInt();
}catch (InputMismatchException e) {
continue;
}
switch (choice) {
case 2: performSubtract();
break;
...
case 5: exit();
break;
}
}while(choice >0 && choice <5);
userInput.close();
}
public static void performSubtract () {
//catch error statement.
try {
numberOne = userInput.nextFloat();
numberTwo= userInput.nextFloat();
answer= numberOne-numberTwo;
} catch (Exception e) {
System.out.println("You have entered invalid floats. please re-enter: ");
numberOne = userInput.nextFloat();
numberTwo= userInput.nextFloat();
}
System.out.printf("Please enter two floats to subtraction, separated by a space: %.1f %.1f\n", numberOne, numberTwo);
System.out.printf("Result of subtraction %.1f and %.1f is %.1f\n", numberOne, numberOne, answer);
System.out.println("\nPress enter key to continue...");
}
}
I believe the issue is that you are not clearing the problem token from the scanner.
Your catch statement prints an error message, and then goes around to try and parse the same token into an int or float again.
You might check here: https://www.geeksforgeeks.org/scanner-nextint-method-in-java-with-examples/
It looks like you need to call userInput.next() to advance past the invalid token.
Also, hasNextInt() will let you avoid the catch altogether if you prefer.
Your error lies in the fact that Scanner.nextFloat, when reading an invalid input, does not advance the current token. This means that when you call nextFloat twice again in the catch statement, you once again read the tokens s and s, the first of which will cause an InputMismatchException to be thrown once again. You should change your performSubtract method to look something like this:
public static void performSubtract () {
//catch errors
System.out.println("Please enter two floats to subtraction, separated by a space");
userInput.nextLine();//ignore the new line
do {
try {
String[] nextLineTokens = userInput.nextLine().split("\\s+");
if(nextLineTokens.length != 2)
{
System.out.println("You have not entered two floats. please re-enter:");
continue;
}
numberOne = Float.parseFloat(nextLineTokens[0]);
numberTwo = Float.parseFloat(nextLineTokens[1]);
answer= numberOne-numberTwo;
break;
}
catch (Exception e) {
System.out.println("You have entered invalid floats. please re-enter: ");
}
} while (true);
System.out.printf("You entered: %.1f %.1f\n", numberOne, numberTwo);
System.out.printf("Result of subtraction %.1f minus %.1f is %.1f\n", numberOne, numberTwo, answer);
System.out.println("\nPress enter key to continue...");
userInput.nextLine();
}
Additionally, your parsing code continues if you enter an invalid input, but exits if you type in a number that is not 1-5. If it is the first time that you read in input, the code exits for invalid inputs as well. You should probably change your parse iteration loop as so:
public static void main(String[] args) {
while(choice != 5) {
//this menu statement has to be repeated unless 5 is entered (exit the
//program)
System.out.println("Welcome to <dj's> Handy Calculator\n\n\t 1. Addition \n\t 2. Subtraction\n\t 3. Multiplication\n\t 4. Division\n\t 5. Exit\n\n");
System.out.print("What would you like to do? ");
try {
choice = userInput.nextInt();
}
catch (InputMismatchException e) {
userInput.next();
continue;
}
switch (choice) {
case 2: performSubtract();
break;
// ...
case 5: exit();
break;
}
}
userInput.close();
}
To the first question: try-catch block are usually used to see if your code are running through without error. By what you explain what you are trying to do, I would instead use a while-loop before the assignment for numberOne and numberTwo whether the input was float or not like:
// pseudo
while(input != float || input2 != float)
{
print(please reenter)
}
numberOne = input
numberTwo = input2

Why is this Scanner assigning null to a variable?

For a college assessment I'm having to use a Scanner called sc with a class-level scope, and the entirety of the program has to be contained in a single class. The main method calls a menu() method, which uses the Scanner and a for loop to call one of two methods in response to user input.
One of the two methods uses the Scanner to calculate the factorial of an input integer. Once the method is executed, the for loop in menu() continues. To avoid an InputMismatchException due to the user entering a float, I used try/catch. However when the program returns back to the menu() for loop the Scanner causes an InputMismatchException when assigning to choice. How can I get Scanner to prompt the user for input again? Apologies if I'm missing something obvious, this is the first programming language I've ever learned. This should be the stripped down compilable code:
package summativeassessment;
import java.util.InputMismatchException;
import java.util.Scanner;
public class SummativeAssessment {
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
menu();
}
public static void menu(){
String fName;
String sName;
System.out.print("Enter your first name: ");
fName = sc.next();
System.out.print("Enter your last name: ");
sName = sc.next();
try{
for(int choice = 1; choice!=0;){
System.out.print("Option 1 to generate username. Option 2 to calculate factorial. Press 0 to quit: ");
choice = sc.nextInt();
switch(choice){
case 2:
System.out.println(fName+" "+sName+", you have selected option 2");
numberFactorial();
break;
case 0:
break;
default:
System.out.println("Invalid option. Please try again.");
}
}
} catch(InputMismatchException ex){
String msg = ex.getMessage();
System.out.println(msg);
}
}
public static void numberFactorial(){
System.out.print("Enter a number: ");
try{
int numIn = sc.nextInt();
long result = numIn;
if(numIn>0){
for(int factor = 1; factor<numIn; factor++){
result *= factor;
if(factor==numIn-1){
System.out.println("The factorial is "+result);
}
}
}
else{
System.out.println("Enter a positive integer greater than 0");
}
}
catch(InputMismatchException ex){
System.out.println("Input invalid");
}
}
}
I debugged your code and got this result:
If you enter a float as input you trigger the InputMismatchException but there is still something in your buffer. So the next time sc.nextInt() is called, it won't wait until you input a value because something is in the buffer already, so it takes the next value out of the buffer and tries to interpret is as an integer. However, it fails to do so, because it is not an integer, so an InputMismatchException is raised again and caught in your menu's catch, now leading to the exit of the program.
The solution is to draw whatever is left in the buffer after the exception was raised the first time.
So the working code will contain a buffer clearing sc.next() inside the exception:
public static void numberFactorial(){
System.out.print("Enter a number: ");
try{
int numIn = sc.nextInt();
long result = numIn;
if(numIn>0){
for(int factor = 1; factor<numIn; factor++){
result *= factor;
if(factor==numIn-1){
System.out.println("The factorial is "+result);
}
}
}
else{
System.out.println("Enter a positive integer greater than 0");
}
}
catch(InputMismatchException ex){
System.out.println("Input invalid");
sc.next();
}
}

Not Able to Use the Scanner Object on changing the position where I create it

I just started learning java on my own and I'm facing a problem with this simple calculator program that I wrote.
In the first code, I get the expected output, if I input integers with nextInt() (operands for arithmetic operations) before taking the string input through nextLine() (the arithmetic operations, ADD, SUB, MUL).
That is, in total I take 3 inputs.
It checks for the conditions and operates according to the condition which is true.
But if I change the position, i.e., first take the String input (the operations) and then the integer input (the numbers), it does not take any input for the String (operations). It also doesn't check for any conditions.
That is, in this case, I am able to input only the 2 integers and not the operation string.
What's wrong with the code? I have run it in Eclipse and Netbeans and the result is same.
The one which gives right output
import java.util.Scanner;
public class Test
{
public static void main(String args[])
{
float fnum, snum, result;
Scanner input= new Scanner(System.in);
System.out.println("What Operation do you want to perform?");
System.out.println("Enter The Choice \n\"ADD\" -For Addition");
System.out.println("\"SUB\"- For Subtraction");
System.out.println("\"MUL\"- For Multiplication");
System.out.println("\"DIV\"- For Division");
/**/String a= input.nextLine(); // on changing its position in the 2nd one
System.out.print("Enter the First Number:");
fnum=input.nextInt();
System.out.println("The First Number Entered is : "+fnum);
System.out.print("Enter the Second Number:");
snum=input.nextInt();
System.out.println("The Second Number Entered is: "+snum);
if(a.equals("ADD"))
{
result= fnum+snum;
System.out.print("The Result After ADDITION of the Two Numbers Is:");
System.out.println(result);
}
else if(a.equals("SUB"))
{
result=fnum-snum;
System.out.print("The Result After SUBSTRACTION of the Two Numbers Is:");
System.out.println(result);
}
else if(a.equals("MUL"))
{
result=fnum*snum;
System.out.print("The Result After MULTIPLICATION of the Two Numbers Is:");
System.out.println(result);
}
else if(a.equals("DIV"))
{
result=fnum/snum;
System.out.print("The Result After DIVISION of the Two Numbers Is:");
System.out.println(result);
}
else
{
System.out.println("Invalid Case");
}
}
}
The Second one which has the problem
import java.util.Scanner;
public class Test
{
public static void main(String args[])
{
float fnum, snum, result;
Scanner input= new Scanner(System.in);
System.out.print("Enter the First Number:");
fnum=input.nextInt();
System.out.println("The First Number Entered is : "+fnum);
System.out.print("Enter the Second Number:");
snum=input.nextInt();
System.out.println("The Second Number Entered is: "+snum);
System.out.println("What Operation do you want to perform?");
System.out.println("Enter The Choice \n\"ADD\" -For Addition");
System.out.println("\"SUB\"- For Subtraction");
System.out.println("\"MUL\"- For Multiplication");
System.out.println("\"DIV\"- For Division");
/**/String a= input.nextLine();// on changing the place of this, goes directly to the last else case, takes no input
if(a.equals("ADD"))
{
result= fnum+snum;
System.out.print("The Result After ADDITION of the Two Numbers Is:");
System.out.println(result);
}
else if(a.equals("SUB"))
{
result=fnum-snum;
System.out.print("The Result After SUBSTRACTION of the Two Numbers Is:");
System.out.println(result);
}
else if(a.equals("MUL"))
{
result=fnum*snum;
System.out.print("The Result After MULTIPLICATION of the Two Numbers Is:");
System.out.println(result);
}
else if(a.equals("DIV"))
{
result=fnum/snum;
System.out.print("The Result After DIVISION of the Two Numbers Is:");
System.out.println(result);
}
else
{
System.out.println("Invalid Case");
}
}
}
Basically, you are still on the same line. so calling input.nextLine(); Advances this scanner past the current line and returns the input that was skipped.
Check the documentation for nextLine() method for a detailed explanation.
To achieve what you want you need to call nextLine twice. i.e.
input.nextLine();//to complete the current line
String a = input.nextLine();//To get the user input

java - trying to catch exception from scanner in a loop [duplicate]

I'm trying to make a small program more robust and I need some help with that.
Scanner kb = new Scanner(System.in);
int num1;
int num2 = 0;
System.out.print("Enter number 1: ");
num1 = kb.nextInt();
while(num2 < num1) {
System.out.print("Enter number 2: ");
num2 = kb.nextInt();
}
Number 2 has to be greater than number 1
Also I want the program to automatically check and ignore if the user enters a character instead of a number. Because right now when a user enters for example r instead of a number the program just exits.
Use Scanner.hasNextInt():
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
Here's a snippet to illustrate:
Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt()) sc.next();
int num1 = sc.nextInt();
int num2;
System.out.print("Enter number 2: ");
do {
while (!sc.hasNextInt()) sc.next();
num2 = sc.nextInt();
} while (num2 < num1);
System.out.println(num1 + " " + num2);
You don't have to parseInt or worry about NumberFormatException. Note that since the hasNextXXX methods don't advance past any input, you may have to call next() if you want to skip past the "garbage", as shown above.
Related questions
How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
the condition num2 < num1 should be num2 <= num1 if num2 has to be greater than num1
not knowing what the kb object is, I'd read a String and then trying Integer.parseInt() and if you don't catch an exception then it's a number, if you do, read a new one, maybe by setting num2 to Integer.MIN_VALUE and using the same type of logic in your example.
This should work:
import java.util.Scanner;
public class Test {
public static void main(String... args) throws Throwable {
Scanner kb = new Scanner(System.in);
int num1;
System.out.print("Enter number 1: ");
while (true)
try {
num1 = Integer.parseInt(kb.nextLine());
break;
} catch (NumberFormatException nfe) {
System.out.print("Try again: ");
}
int num2;
do {
System.out.print("Enter number 2: ");
while (true)
try {
num2 = Integer.parseInt(kb.nextLine());
break;
} catch (NumberFormatException nfe) {
System.out.print("Try again: ");
}
} while (num2 < num1);
}
}
Try this:
public static void main(String[] args)
{
Pattern p = Pattern.compile("^\\d+$");
Scanner kb = new Scanner(System.in);
int num1;
int num2 = 0;
String temp;
Matcher numberMatcher;
System.out.print("Enter number 1: ");
try
{
num1 = kb.nextInt();
}
catch (java.util.InputMismatchException e)
{
System.out.println("Invalid Input");
//
return;
}
while(num2<num1)
{
System.out.print("Enter number 2: ");
temp = kb.next();
numberMatcher = p.matcher(temp);
if (numberMatcher.matches())
{
num2 = Integer.parseInt(temp);
}
else
{
System.out.println("Invalid Number");
}
}
}
You could try to parse the string into an int as well, but usually people try to avoid throwing exceptions.
What I have done is that I have defined a regular expression that defines a number, \d means a numeric digit. The + sign means that there has to be one or more numeric digits. The extra \ in front of the \d is because in java, the \ is a special character, so it has to be escaped.
I see that Character.isDigit perfectly suits the need, since the input will be just one symbol.
Of course we don't have any info about this kb object but just in case it's a java.util.Scanner instance, I'd also suggest using java.io.InputStreamReader for command line input. Here's an example:
java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
try {
reader.read();
}
catch(Exception e) {
e.printStackTrace();
}
reader.close();
What you could do is also to take the next token as a String, converts this string to a char array and test that each character in the array is a digit.
I think that's correct, if you don't want to deal with the exceptions.

Categories