How can I remove this java exception error in my code? - java

When I input a string into the code below by mistake as a test, I get a red java error message in my console. However, within my if statement I added an else part which should end the program if the user doesn't input the if statement condition i.e a number between 0-100. Why this is and how can I fix it?
MY CODE
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int decimal = input.nextInt();
if (decimal > 0 && decimal <= 100) {
//code
}
else {
System.exit(0);
}
When I input a string this message gets displayed. However, I just wanted to tell the user they exerted the wrong value and I wanted the program to quit.
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at MainHandler.main(MainHandler.java:22)
I did try use hasNextInt at one point to try get rid of the exception error but I get an error when I use hasNextInt. https://imgur.com/a/OK8r3RH

Try with something like this. You surround your input inside a try-catch and as long as you get an Exception, you ask the user to put a number again. As soon as the input is valid (a number) you can proceed with your code:
boolean canProceed = false;
int number = -1;
while (!canProceed) {
try {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
number = Integer.parseInt(input.nextLine());
canProceed = true;
} catch (Exception e) {
System.out.println("Invalid input.");
}
}
if (number > 0 && number <= 100) {
System.out.println("That's fine");
}
else {
System.exit(0);
}

You would need double if you are entering decimal numbers and put your code inside try/catch block
try{
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
double decimal = input.nextDouble();
if (decimal > 0 && decimal <= 100) {
}
else {
System.exit(0);
}
}catch (Exception e){
System.out.println(e);
}

Try binding your code inside try and catch blocks like this:
try{
int decimal = input.nextInt();
if (decimal > 0 && decimal <= 100) {
//code
}
else {
System.exit(0);
}
}
catch(Exception e){
System.out.println("You enter wrong value");
}

The code you posted works just fine if the input is provided from the start. However given your "Enter a number:" message I suppose you want the user to provide the input interactively, in which case you'll have to implement a waiting loop :
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
while (!scanner.hasNextInt()) {
if (scanner.hasNextLine()) {
scanner.nextLine(); // we've got something but it's not a number, discard it
}
}
int decimal = input.nextInt();
if (decimal > 0 && decimal <= 100) {
//code
}
else {
System.exit(0);
}
In this case the loop will continue until it finds an integer to read from the input, discarding lines of input if they don't start with an integer.

I just thought I would throw this in here since it is another flexible alternative to accomplishing the task. It utilizes the Scanner#nextLine() method with input validation to ensure that what is supplied is actually what is expected without the worry of an exception being thrown.
Validation is done using the String#matches() method supplied with a small Regular Expression (RegEx) to insist that numerical digits are supplied and that the supplied value is within the desired inclusive unsigned numerical range of 1 to 100. If the validation fails then the User is expected to try again or enter 'Q' (or anything that starts with Q - case insensitive) to quit.
Scanner input = new Scanner(System.in);
int intValue = 0;
String numberString = "";
// Prompt and Input...
while (intValue == 0) {
System.out.print("Enter a number (or 'q' to quit): --> ");
numberString = input.nextLine().toLowerCase();
//Quit..
if (numberString.charAt(0) == 'q') {
System.exit(0);
}
// Integer (unsigned - Range 1 to 100)...
else if (numberString.matches("100|[1-9][0-9]{1}?")) {
intValue = Integer.parseInt(numberString);
}
else {
System.err.println("Invalid numerical value supplied or the supplied");
System.err.println("value is not in the inclusive range of 1 to 100!");
System.err.println("Try Again...");
System.err.println();
}
}
//Your processing code here.
System.out.println("The value you entered is: --> " + intValue);
Explanation for the RegEx used within the String#matches() method:
100|[1-9][0-9]{1}?
1st Alternative 100
100 matches the characters 100 literally (case sensitive)
2nd Alternative [1-9][0-9]{1}?
Match a single character present in the list below [1-9]
1-9 a single character in the range between 1 (index 49) and 9 (index 57) (case sensitive)
Match a single character present in the list below [0-9]{1}?
{1}? Quantifier — Matches exactly one time (meaningless quantifier)
0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
If you want to change your numerical range then you may find this site useful.

Related

Java: show different results depending on User Console Input without try...catch statement

I try to write a programm in Java that gets user input using Scanner Class. The user has to enter any positive integer number. Depending on user actions, the results should be as follows:
The user has entered not an integer number -> the programm prints the message
Oops! You entered something different, but not an integer number, try again
The user has entered not a positive integer number -> the programm prints the message
You entered not a positive integer number, try again
The user has entered a positive integer number -> the programm prints the number
User's positive integer number - ...
I have written some code using loop and Scanner class
public static void main(String[] args) {
int userIntNum;
boolean isUserInputCorrect;
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
userIntNum = 0;
System.out.println("Please, enter a positive integer number");
isUserInputCorrect = (sc.hasNextInt() && (userIntNum > 0));
// double console input for correct integer number
while (isUserInputCorrect == false) {
if (!sc.hasNextInt()) {
System.out.println("Oops! You entered something different, but not an integer number, try again");
sc.nextLine();
} else if (sc.nextInt() <= 0) {
System.out.println("You entered not a positive integer number, try again");
sc.nextLine();
} else {
break;
}
}
userIntNum = sc.nextInt();
System.out.println("User's positive integer number - " + userIntNum);
When I put in the console a positive integer number (the correct input), the programm, for some reason, asks me to enter this number twice.
Moreover, if I put first an integer number and then any non-positive number separated by space, it will print this incorrect number. And if I put first an integer number and then not an integer number separated by space, it will throw an exception.
Why does it happen and how can I fix these errors?
First, I would eliminate isUserInputCorrect. You are trying to do too much with it, instead I would loop while userIntNum is less than or equal to zero. Also, try and limit variable scope. Something like,
Scanner sc = new Scanner(System.in);
int userIntNum = -1;
System.out.println("Please, enter a positive integer number");
// double console input for correct integer number
while (userIntNum <= 0) {
if (sc.hasNextInt()) {
userIntNum = sc.nextInt();
} else {
System.out.println("Oops! You entered something different, "
+ "but not an integer number, try again");
sc.nextLine();
}
if (userIntNum <= 0) {
System.out.println("You entered not a positive integer number, try again");
}
}
System.out.println("User's positive integer number - " + userIntNum);
Expanding on Elliott's answer above, I wanted to provide an alternative solution that addresses your following point:
Moreover, if I put first an integer number and then any non-positive
number separated by space, it will print this incorrect number. And if
I put first an integer number and then not an integer number separated
by space, it will throw an exception.
The Scanner class will read tokens individually in a temporal fashion. If you look at the nextInt() function you will see it that throws InputMismatchException which you can explicitly catch.
Additionally, take a look at the Java modulus operator. Since you are explicitly looking for even values, the modulus operator is extremely valuable here.
public static void main(String[] args) {
int userIntNum = 0;
boolean isUserInputCorrect = false;
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
do {
System.out.println("Please, enter a positive integer number");
try {
userIntNum = sc.nextInt();
isUserInputCorrect = (userIntNum > 0 && userIntNum % 2 == 0);
} catch (InputMismatchException ex) {
System.out.println("Invalid input: please enter an integer value");
sc.next();
}
} while(!isUserInputCorrect);
System.out.println("User's positive integer number - " + userIntNum);
}

using string to break out of loop in java

I simply would like to break out of a while true loop if the user enters in "STOP" into the scanner. Currently my scanner only takes in integers and I believe this is where the problem lies. If I try to type in "STOP" I get many errors saying "exception in thread main". Here is a snippet of my code:
public class algorithm {
private Scanner input = new Scanner(System.in);
int n;
while (true){
System.out.println("Eneter a number to check if it is odd or even, then hit enter: ");
System.out.println("Type 'STOP' to end the program");
n = input.nextInt();
String strN = String.valueOf(n); //convert integer to string
if (new String(strN).equals("STOP")){ //if string is STOP, breaks
System.out.println("Thanks for using my program");
break;
}
if (n % 2 == 0){
System.out.println(n+" is even");
continue;
}
else{
System.out.println(n+" is odd");
continue;
I know I am missing some closing curly braces but rest assured they are all there in my actual code. Thanks.
Here is the error I am getting:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at OddOrEven.algorithm.checker(algorithm.java:13)
at OddOrEven.main.main(main.java:7)
You've already identified the problem yourself - your Scanner reads only integers:
int n;
...
n = input.nextInt();
so it's impossible for the variable n (an int) to contain the string "STOP" (and your Scanner throws an exception anyway when you call nextInt() but it encounters a string, such as "STOP", that it cannot convert to an int).
To do this, you need to read strings from the input (probably using Scanner.nextLine()), check whether they are "STOP", and if not, only then attempt to convert them to ints using something like:
int n = Integer.parseInt(mystring)
To handle garbage input (neither STOP nor an integer), wrap the parseInt line in a try-catch block so that you can detect when the input is garbage by catching the Exception
try {
int i = Integer.parseInt(mystring);
// do something with the int
}
catch (NumberFormatException e) {
// display warning message to the user instead
}
See also this related question.
The most simple way is probably to use input.next() instead of input.nextInt(). Using input.next() will read input in as a String, then you can check if the input is equal to "QUIT", if it is not you can use Integer.parseInt to parse the Integer from the read string
Something like below, should work out.
NOTE: havent tested compile errors, just wrote it out(but you get a gist)
public Scanner input = new Scanner(System.in);
int n;
while (true){
System.out.println("Eneter a number to check if it is odd or even, then hit enter: ");
System.out.println("Type 'STOP' to end the program");
n = input.next();
Integer input;
// String strN = String.valueOf(n); //convert integer to string
if (strN.equals("STOP")){ //if string is STOP, breaks
System.out.println("Thanks for using my program");
break;
}
else{
try{
input= Integer.parseInt(strN);
}
catch(Exception e)
{
System.out.println("Please enter a number");
}
}
if (input % 2 == 0){
System.out.println(n+" is even");
continue;
}
else{
System.out.println(n+" is odd");
continue;
}

Throw an error when a string is entered instead of an int [duplicate]

This question already has answers here:
Java input mismatch error using scanner
(3 answers)
Closed 8 years ago.
I am working on homework for my class. I have written a method to throw an error if an incorrect integer is entered and I am trying to give an error message when a string is entered instead of an int but I am not sure how. I am not allowed to use parsInt or built in string methods. I would be grateful for any help.
int playerNum = stdin.nextInt();
while (invalidInteger(playerNum) == -1 || invalidInteger(playerNum) == -2 || invalidInteger(playerNum) == -3)
{
if(invalidInteger(playerNum) == -1)
{
System.out.println("Invalid guess. Must be a positive integer.");
System.out.println("Type your guess, must be a 4-digit number consisting of distinct digits.");
count++;
}
if(invalidInteger(playerNum) == -2)
{
System.out.println("Invalid guess. Must be a four digit integer.");
System.out.println("Type your guess, must be a four digit number consisting of distinct digits.");
count++;
}
if(invalidInteger(playerNum) == -3)
{
System.out.println("Invalid guess. Must have distinct digits.");
System.out.println("Type your guess, must be a four digit number consisting of distinct digits.");
count++;
}
playerNum = stdin.nextInt();
}
Added this snippet to catch the exception. Thanks to almas shaikh.
try {
int playerNum = scanner.nextInt();
//futher code
} catch (InputMismatchException nfe) {
System.out.println("You have entered a non numeric field value");
}
Use the following code:
try {
int playerNum = scanner.nextInt();
//futher code
} catch (InputMismatchException nfe) {
System.out.println("You have entered a non numeric field value");
}
Scanner throws InputMismatchException when you enter string instead of integer. So very next time when you try to enter String it will throw the InputMismatchException exception, you could catch the exception and say you let user know that user has entered invalid input and let him retry.
Check the java doc for nextInt() -- is stdin a Scanner? If so, nextint() will throw an exception if some non-integer text is entered. You would probably want to catch that and print your own pretty error. Though, you might be going even further than the assignment expects. The phrase "throw an error if an incorrect integer is entered" might imply that only integers will be entered. It depends on the instructor/class.
import java.util.*;
public class Test
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
try
{
int i = in.nextInt();
}
catch(InputMismatchException e)
{
e.printStackTrace();
}
}
}
I hope this will server as an example. When you give an char or string. exception is raised.
Well, you can use next() to get the value as a String, then parse the value and see if a String or Integer was entered.
String str = stdin.next();
for (char c:str.toCharArray()) {
if (!Character.isDigit(c)) {
throw new IllegalArgumentException("Invalid character entered: " + c);
}
}

Try-Catch inside a loop

In the below code, I ask the user to give an integer input and if the input is 0 or a negative number, it loops again until the positive number is given. The thing is that if the users presses a letter, my code crashes and despite the fact that I used try-catch in a lot of ways nothing really worked. Any ideas?
I used try-catch inside the loop, but it only worked for one letter input and not correctly.
System.out.print("Enter the number of people: ");
numberOfPeople = input.nextInt();
while (numberOfPeople <= 0) {
System.out.print("Wrong input! Enter the number of people again: ");
numberOfPeople = input.nextInt();
}
The problem in your current code is that you're always trying to read an int so when receiving a non-integer input you can't handle the error in the right way. Modify this to always read a String and convert it into an int:
int numberOfPeople = 0;
while (numberOfPeople <= 0) {
try {
System.out.print("Enter the number of people: ");
numberOfPeople = Integer.parseInt(input.nextLine());
} catch (Exception e) {
System.out.print("Wrong input!");
numberOfPeople = 0;
}
}
//continue with your life...

Set boundaries for integer input

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.
}

Categories

Resources