Cannot continue program execution when throwing exception java - java

I am practicing using the try-catch block to validate user input. Trying so hard to do but don't know why it doesn't work. I tried it both ways. It always pops out InputMismatchException and end the program.
The first one, I followed this video: https://www.youtube.com/watch?v=PWez5mVXACc&t=356s
public int moveStone(int initialStone, int upperBound, int stoneBalance) throws Exception {
int takeStone = 0;
boolean isNumber = false;
do {
if (in.hasNextInt()){
takeStone = in.nextInt();
isNumber =true;
}
if (!in.hasNextInt()) {
if (stoneBalance >= upperBound) {
System.out.println("Invalid move. You must remove between 1 and " + upperBound + " stones.\n");
isNumber = false;
takeStone = in.nextInt();
}
if (stoneBalance < upperBound) {
System.out.println("Invalid move. You must remove between 1 and " + stoneBalance + " stones.\n");
isNumber = false;
takeStone = in.nextInt();
}
}
} while (!(isNumber));
return takeStone;
}
and this, I followed by other tutorials:
public int moveStone(int initialStone, int upperBound, int stoneBalance) throws Exception {
int takeStone = 0;
try {
if (in.hasNextLine()) {
throw new Exception();
} else {
takeStone = in.nextInt();
return takeStone;
}
} catch (Exception e) {
System.out.println("Invalid move");
if (stoneBalance >= upperBound) {
System.out.println("You must remove between 1 and " + upperBound + " stones.\n");
takeStone = in.nextInt();
return takeStone;
}
if (stoneBalance < upperBound) {
System.out.println("You must remove between 1 and " + stoneBalance + " stones.\n");
takeStone = in.nextInt();
return takeStone;
}
}
return -1;
}

You are throwing Exception
if (in.hasNextLine()) {
throw new Exception();
}
And catching only InputMismatchException. Use Exception in catch
catch (Exception e){

I got where the problem is: the user input still remains in the Scanner buffer.
When it passes the invalid input, it goes to the catch block. This operation is correct.
However, when the program has to prompt the user to give another input, the invalid input still in the Scanner that it goes straight to the takeStone = in.nextInt(). The program jumps out because of InputMismatchException directly.
The solution is to put another Scanner to take the token before prompting the user input.
public int moveStone(int initialStone, int upperBound, int stoneBalance) throws Exception {
int takeStone = 0;
try {
if (!in.hasNextInt()) {
throw new Exception();
} else {
takeStone = in.nextInt();
return takeStone;
}
} catch (Exception e) {
if (stoneBalance >= upperBound) {
System.out.println("Invalid move. You must remove between 1 and " + upperBound + " stones.\n");
in.next(); // input still in the Scanner buffer, use another scanner to take this input
takeStone = in.nextInt();
return takeStone;
}
if (stoneBalance < upperBound) {
System.out.println("Invalid move. You must remove between 1 and " + stoneBalance + " stones.\n");
in.next();
takeStone = in.nextInt();
return takeStone;
}
}
return -1;
}

Related

Java guess game. How do I use data validation to check if a number is within a certain range?

I need help coding a set of statements of data validation that checks if a user entry is within a range of 0 and 100, and anything the user types that ISNT a non-decimal integer between 1 and 100 should display an error message. Also I need a way to code how I can get a "goodbye" output to only display if the user enters "n" not "n" and "y." N meaning no and y meaning yes.
Heres my code.
import java.util.Scanner;
public class GuessingGameCalc {
private static void displayWelcomeMessage(int max) {
System.out.println("Welome to the Java Guessing Game!");
System.out.println(" ");
System.out.println("I'm thinking of a number between 1 and" + " " + max + " " + "let's see if you guess what it is!");
System.out.println(" ");
}
public static int calculateRandomValue(int max) {
double value = (int) (Math.random() * max + 1);
int number = (int) value;
number++;
return number;
}
public static void validateTheData(int count) {
if( count < 3) {
System.out.println("Good job!");
} else if (count < 7) {
System.out.println("Need more practice.");
} else{
System.out.println("Need way more practice.");
}
}
public static void main(String[] args) {
final int max = 100;
String prompt = "y";
displayWelcomeMessage(max);
int unit = calculateRandomValue(max);
Scanner sc = new Scanner(System.in);
int counter = 1;
while (prompt.equalsIgnoreCase("y")) {
while (true) {
System.out.println("Please enter a number.");
int userEntry = sc.nextInt();
if (userEntry < 1 || userEntry > max) {
System.out.println("Invalid guess! Guess again!");
continue;
}
if (userEntry < unit) {
if ( (unit - userEntry) > 10 ) {
System.out.println("Way Too low! Guess higher!");
} else {
System.out.println("Too low! Guess higher!");
}
} else if (userEntry > unit) {
if( (userEntry - unit) > 10 ){
System.out.println("Way Too high! Guess lower!");
} else {
System.out.println("Too high! Guess lower!");
}
} else {
System.out.println("Congratulations! You guessed it in" + " " + counter + " " + "tries!\n");
validateTheData(counter);
break;
}
counter++;
}
System.out.println("Would you like to try again? Yes or No?");
prompt = sc.next();
System.out.println("Goodbye!");
}
}
}
Instead of using .nextInt() rather use .nextLine(), which returns a String and then parse it to an int and catch the NumberFormatException
So basically you'll have this structure:
try {
int userEntry = Integer.parseInt(sc.nextLine());
...
} catch (NumberFormatException nfe) {
System.out.println("Please enter a valid number.");
}
Oh, just a comment on the rest of your code. You don't really need two while loops, one will be more than sufficient.

How can I make the code catch the error when the input provided is not a number?

The program checks the user input and determines if it's positive or negative.
How can I catch the error when the user provides an invalid input (non-integer) such as "444h" or "ibi".
I was thinking the final else statement would catch the exception but it does not.
import java.util.Scanner;
public class Demo
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter any number: ");
int num = scan.nextInt();
scan.close();
if(num > 0)
{
System.out.println(num+" is positive");
}
else if(num < 0)
{
System.out.println(num+" is negative");
}
else if(num == 0)
{
System.out.println(num+" is neither positive nor negative");
}
else
{
System.out.println(num+" must be an integer");
}
}
}
I expect the program to catch the exception and prompt input of a valid integer
Simply wrap your code in a try..catch block.
Full code:
import java.util.Scanner;
import java.util.InputMismatchException;
class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
Scanner scan = new Scanner(System.in);
System.out.print("Enter any number: ");
try {
int num = scan.nextInt();
if (num > 0) {
System.out.println(num + " is positive");
} else if (num < 0) {
System.out.println(num + " is negative");
} else if (num == 0) {
System.out.println(num + " is neither positive nor negative");
}
} catch (InputMismatchException e) {
System.out.println("Error: Value Must be an integer");
}
scan.close();
}
}
Good luck :)
int num = 0;
try{
num =input.nextInt();
}catch(InputMismatchException ex) {
System.out.println("Enter Integer Value Only");
}
You have to write int num = scan.nextInt(); this statement inside try block if you get non-integer value from input then InputMismatchException will arise then catch block will executed.
First off, don't close the Scanner if you plan on using it again during the operation of your application. Once you close it, you will need to restart your application in order to use it again.
As already mentioned, you could utilize a try/catch on the Scanner#nextInt() method:
Scanner scan = new Scanner(System.in);
int num = 0;
boolean isValid = false;
while (!isValid) {
System.out.print("Enter any number: ");
try {
num = scan.nextInt();
isValid = true;
}
catch (InputMismatchException ex) {
System.out.println("You must supply a integer value");
isValid = false;
scan.nextLine(); // Empty buffer
}
}
if (num > 0) {
System.out.println(num + " is positive");
}
else if (num < 0) {
System.out.println(num + " is negative");
}
else if (num == 0) {
System.out.println(num + " is neither positive nor negative");
}
Or you could use the Scanner#nextLine() method instead which accepts string:
Scanner scan = new Scanner(System.in);
String strgNum = "";
boolean isValid = false;
while (!isValid) {
System.out.print("Enter any Integer value: ");
strgNum = scan.nextLine();
/* See if a signed or unsigned integer value was supplied.
RegEx is used with the String#matches() method for this.
Use this RegEx: "-?\\d+(\\.\\d+)?" if you want to allow
the User to enter a signed or unsigned Integer, Long,
float, or double values. */
if (!strgNum.matches("-?\\d+")) {
System.out.println("You must supply a numerical value (no alpha characters allowed)!");
continue;
}
isValid = true; // set to true so as to exit loop
}
int num = Integer.parseInt(strgNum); // Convert string numerical value to Integer
/* Uncomment the below line if you use the other RegEx. You would have to also
comment out the above line as well. */
// double num = Double.parseDouble(strgNum); // Convert string numerical value to double
if (num > 0) {
System.out.println(num + " is positive");
}
else if (num < 0) {
System.out.println(num + " is negative");
}
else if (num == 0) {
System.out.println(num + " is neither positive nor negative");
}
Use regex to check if input is a number
import java.util.regex.*;
Pattern.matches("[0-9]+", "123"); // this will return a boolean

Catch invalid input and return to input prompt JAVA

I am very new to Java and as part of my college course I have to write a program that carries out some basic functions. Part of this program is that it needs to calculate the factorial of a number that the user inputs. If the user inputs a negative number then it must prompt for a positive number. I have got it to do this.
But if the user enters a fraction such as 2.2 then the program should present the user with an error and prompt for valid data. I believe some sort or try-catch should be implemented but so far I have had no success in getting this to work, after spending many hours on it. Any ideas how to get the program to catch the InputMismatchException error and prompt user for input again?
The relevant block of code from the program is below...
public static void factorialNumber() {
int factorial = 1;
boolean valid;
int number = 0;
do {
System.out.println("Please enter a number: ");
number = sc.nextInt();
valid = number > 0;
if (!valid) {
System.out.println("ERROR Please enter a positive number");
}
} while (!valid);
if (number < 0) {
System.out.println("***Error***: Please enter a positive number ... ");
factorialNumber();
}
if (number > 0) {
System.out.print("The factorial is: " + number + " ");
}
for (int i = 1; i <= number; i++) {
factorial *= i;
if ((number - i) > 0) {
System.out.print("x " + (number - i) + " ");
}
}
System.out.println("= " + factorial);
}
You can use Double class to parse the user input and then get only correct values. Like this:
public static void factorialNumber() {
int factorial = 1;
boolean valid;
int number = 0;
String userInput;
do {
System.out.println("Please enter a number: ");
userInput = sc.nextLine();
valid = validateUserInput(userInput);
} while (!valid);
number = Double.valueOf(userInput).intValue();
System.out.print("The factorial is: " + number + " ");
for (int i = 1; i <= number; i++) {
factorial *= i;
if ((number - i) > 0) {
System.out.print("x " + (number - i) + " ");
}
}
System.out.println("= " + factorial);
}
private static boolean validateUserInput(String userInput) {
if (userInput == null) {
System.out.println("You should enter a number!");
return false;
}
Double userInputNumber;
try {
userInputNumber = Double.valueOf(userInput);
} catch (Exception e) {
System.out.println("Please enter a valid number value.");
return false;
}
if (userInputNumber <= 0) {
System.out.println("ERROR Please enter a positive number");
return false;
} else if (userInputNumber - userInputNumber.intValue() > 0) {
System.out.println("ERROR You entered a fractional number!");
return false;
}
return true;
}

How to prevent string from printing repeatedly in while loop?

I'm currently working on some exercises given to me by my teacher. These are for the holidays so I won't be able to ask for help there.
I have this piece of code which creates a multiplication table from an integer defined by the user, ranging from a minimum and maximum also defined by the user.
Before setting any of my variables to the next integer in my Scanner, I do a check to see if the Scanner actually has an integer. This works fine but I don't want it to print out the error message a billion times.
Any tips/tricks or other special ways of getting around this?
public class MultiplicationTable
{
private int intervalMin;
private int intervalMax;
private int multiplier;
private int result;
private Scanner sc;
public MultiplicationTable()
{
multiplier = 0;
intervalMin = 0;
sc = new Scanner(System.in);
while (multiplier == 0)
{
System.out.println("Please enter the integer you wish to show the table for");
if (sc.hasNextInt())
{
multiplier = sc.nextInt();
}
else
{
System.out.println("Input is not an integer\n");
}
}
while (intervalMin == 0)
{
System.out.println("\nPlease enter the integer defining the start of the table");
if (sc.hasNextInt())
{
intervalMin = sc.nextInt();
}
else
{
System.out.println("Input is 0 or not an integer\n");
}
}
while (intervalMax == 0)
{
System.out.println("\nPlease enter the integer defining the end of the table");
if (sc.hasNextInt())
{
int i = sc.nextInt();
if (i > intervalMin)
{
intervalMax = i;
}
else
{
System.out.println("\nEnd integer must be greater than start integer");
}
}
else
{
System.out.println("Input is 0 or not an integer");
}
}
System.out.println("\nTable for integer " + multiplier + " from " + intervalMin + " to " + intervalMax + "\n");
for (int i = intervalMin; i <= intervalMax; i++)
{
result = i * multiplier;
System.out.println(i + " * " + multiplier + " = " + result);
}
}
}
You didn't consume what user entered into the scanner buffer, that's why sc.hasNextInt() keeps getting executed without waiting for the next user input.
The solution is to add sc.nextLine() after the if condition.
For example:
boolean gotInteger = false;
while (!gotInteger) {
System.out.println("Please enter the integer you wish to show the table for");
if (sc.hasNextInt()) {
multiplier = sc.nextInt();
gotInteger = true;
} else {
System.out.println("Input is not an integer\n");
}
sc.nextLine();
}
Pleas try this, just wrap all your code inside try catch:
try {
while (intervalMax == 0) {
System . out . println("\nPlease enter the integer defining the end of the table");
if (sc . hasNextInt()) {
int i = sc . nextInt();
if (i > intervalMin) {
intervalMax = i;
} else {
throw new Exception("\nEnd integer must be greater than start integer");
}
}
}
} catch (Exception e) {
System . out . println(e . getMessage());
}

Scanner NoSuchElementException

I'm having a problem with my Java assignment. I'm getting an unexpected exception, specifically:
java.util.NoSuchElementException: No line found
I am using Scanner(System.in) and the program is continually reading nothing and repeating the "invalid format" exception text. If I enter a correctly valued int, the first part passes and then the double part immediately goes into this exception. If I enter an incorrectly valued int, then it starts looping the exception.
Here is my code:
import java.util.Scanner;
public class Program_4 {
public static void main(String[] args) {
getValidInt("Enter an integer from 5 to 50",5,50);
getValidDouble("Enter a double from 5.0 to 50.0",5.0,50.0);
getValidString("Enter a string with length from 5 to 8 characters",5,8);
}
public static int getInt(String prompt)
{
Scanner sc = new Scanner(System.in);
int i = 0;
boolean isValid;
do
{
try
{
System.out.print(prompt + ": ");
i = Integer.parseInt(sc.nextLine());
isValid = true;
}
catch (Exception e)
{
System.out.println(e);
System.out.print("Invalid Format: ");
isValid = false;
}
}
while (isValid == false);
sc.close();
return i;
}
public static int getValidInt(String prompt, int min, int max)
{
int i = 0;
boolean isValid = false;
do
{
i = getInt(prompt);
if(i < min) System.out.println("Value must be >= " + min);
else if(i > max) System.out.println("Value must be <= " + max);
else isValid = true;
} while (isValid == false);
return i;
}
public static double getDouble(String prompt)
{
Scanner sc = new Scanner(System.in);
double i = 0.0;
boolean isValid;
do
{
try
{
System.out.print(prompt + ": ");
i = Double.parseDouble(sc.nextLine());
isValid = true;
}
catch (Exception e)
{
System.out.println(e);
System.out.println("Invalid Format: ");
isValid = false;
}
} while (isValid == false);
sc.close();
return i;
}
public static double getValidDouble(String prompt, double min, double max)
{
int i = 0;
boolean isValid = false;
do
{
i = getInt(prompt);
if(i < min) System.out.println("Value must be >= " + min);
else if(i > max) System.out.println("Value must be <= " + max);
else isValid = true;
} while (isValid == false);
return i;
}
public static String getString(String prompt)
{
Scanner sc = new Scanner(System.in);
String i="";
boolean isValid;
do
{
try
{
System.out.print(prompt + ": ");
i = sc.nextLine();
isValid = true;
}
catch (Exception e)
{
System.out.print("Invalid Format: ");
isValid = false;
}
} while (isValid == false);
sc.close();
return i;
}
public static String getValidString(String prompt, int min, int max)
{
String i;
boolean isValid = false;
do
{
i = getString(prompt);
if(i.length() < min) System.out.println("String must be more than " + min + " characters.");
else if(i.length() > max) System.out.println("String must be more than " + max + " characters.");
else isValid = true;
} while (isValid == false);
return i;
}
}
You have more than one Scanner that you close, which closes the underlying InputStream, therefore another Scanner can no longer read from the same InputStream and a NoSuchElementException results.
For console apps, use a single Scanner to read from System.in.
Since you print out the same message in all three places where an exception is caught, it is difficult to say with any certainty what is going on:
Use printStackTrace() to find out where the exception is happening
Don't catch Exception like that. Catch the exceptions that you are expecting and that your code is designed to handle. If you catch Exception you could end up catching all sorts of unexpected exceptions (NPE, end of file, etc) ... and incorrectly reporting them as "Invalid format".

Categories

Resources