In the below code I am attempting to allow the program to catch an exception for an invalid input from user but still allow the program to loop back to the start of the method once exception has been caught. However in my example once there is an exception the program terminates. How can I rectify this? Thank a lot in advance!
public static void add() {
// Setting up random
Random random = new Random();
// Declaring Integers
int num1;
int num2;
int result;
int input;
input = 0;
// Declaring boolean for userAnswer (Defaulted to false)
boolean correctAnswer = false;
do {
// Create two random numbers between 1 and 100
num1 = random.nextInt(100);
num1++;
num2 = random.nextInt(100);
num2++;
// Displaying numbers for user and getting user input for answer
System.out.println("Adding numbers...");
System.out.printf("What is: %d + %d? Please enter answer below", num1, num2);
result = num1 + num2;
do {
try {
input = scanner.nextInt();
} catch (Exception ex) {
// Print error message
System.out.println("Sorry, invalid number entered for addition");
// flush scanner
scanner.next();
correctAnswer=false;
}
} while (correctAnswer);
// Line break for code clarity
System.out.println();
// if else statement to determine if answer is correct
if (result == input) {
System.out.println("Well done, you guessed corectly!");
correctAnswer = true;
} else {
System.out.println("Sorry incorrect, please guess again");
}
} while (!correctAnswer);
}// End of add
I'm not quite sure about the exceptions part, but have you maybe though about just using if statements?
Scanner has a method 'hasNextInt' which you can use to check that the the input is na int. For example:
Scanner scan = new Scanner(System.in);
int i=0;
boolean correctAnswer = false;
while(correctAnswer == false){
if(scan.hasNextInt()){
i = scan.nextInt(); correctAnswer = true;
}else{ System.out.println("Invalid entry");
correctAnswer = false;
scan.next();
}
System.out.println(i);
}
Sorry that it doesn't actually directly answer your question, but I though you might want to know about this possible way too. :)
Instead of throw an exception maybe you can use the method hasNextInt() which returns true if the token is a number.
But if you want absolutely use the try catch block, you have to remove the scanner.next() instrsctions because when nothings available on the buffer, it's throws an NoSuchElementException
I think solution i am giving can be improved but this is simple modification to fix your code: (just add new condition variable to check if further input/ans attempts required)
Hope it helps - MAK
public class StackTest {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws InterruptedException{
// Setting up random
Random random = new Random();
// Declaring Integers
int num1;
int num2;
int result;
int input;
input = 0;
// Declaring boolean for userAnswer (Defaulted to false)
boolean correctAnswer = false;
//MAK: Add new condition for checking need of input
boolean needAnswer = true;
do {
// Create two random numbers between 1 and 100
num1 = random.nextInt(100);
num1++;
num2 = random.nextInt(100);
num2++;
// Displaying numbers for user and getting user input for answer
System.out.println("Adding numbers...");
System.out.printf("What is: %d + %d? Please enter answer below",
num1, num2);
result = num1 + num2;
while(needAnswer){
try {
input = scanner.nextInt();
needAnswer = false;
} catch (Exception ex) {
// Print error message
System.out.println("Sorry, invalid number entered for addition");
// flush scanner
scanner.next();
needAnswer = true;
}
} ;
// Line break for code clarity
System.out.println();
// if else statement to determine if answer is correct
if (result == input) {
System.out.println("Well done, you guessed corectly!");
correctAnswer = true;
} else {
System.out.println("Sorry incorrect, please guess again");
needAnswer = true;
}
} while (!correctAnswer);
}
}
If you want to have the following:
1) Ask the user how much is x + y
2) Let the user answer
3) If answer is invalid (e.g. user typed in "www"), let the user type his answer to question 1) again
than you should replace your inner do-while loop with the following:
boolean validInput = true;
do {
try {
input = scanner.nextInt();
} catch (Exception ex) {
// Print error message
System.out.println("Sorry, invalid number entered for addition. Please enter your answer again.");
// flush scanner
scanner.next();
validInput = false;
}
} while (!validInput);
Related
must create a java application that will determine and display sum of numbers as entered by the user.The summation must take place so long the user wants to.when program ends the summation must be displayed as follows
e.g say the user enters 3 numbers
10 + 12+ 3=25
and you must use a while loop
Here's a function to do just that. Just call the function whenever you need.
Ex: System.out.println(parseSum("10 + 12+ 3")) → 25
public static int parseSum(String input) {
// Removes spaces
input = input.replace(" ", "");
int total = 0;
String num = "";
int letter = 0;
// Loop through each letter of input
while (letter < input.length()) {
// Checks if letter is a number
if (input.substring(letter, letter+1).matches(".*[0-9].*")) {
// Adds that character to String
num += input.charAt(letter);
} else {
// If the character is not a number, it turns the String to an integer and adds it to the total
total += Integer.valueOf(num);
num = "";
}
letter++;
}
total += Integer.valueOf(num);
return total;
}
The while loop is essentially a for loop though. Is there a specific reason why you needed it to be a while loop?
There is a lot of ways to achieve this. Here an example of code that could be improve (for example by catching an InputMismatchException if the user doesn't enter a number).
Please for the next time, post what you have tried and where you stuck on.
public static void main (String[] args) {
boolean playAgain = true;
while(playAgain) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the first number : ");
int nb1 = sc.nextInt();
System.out.println("Ok! I got it! Please enter the second number : ");
int nb2 = sc.nextInt();
System.out.println("Great! Please enter the third and last number : ");
int nb3 = sc.nextInt();
int sum = nb1+nb2+nb3;
System.out.println("result==>"+nb1+"+"+nb2+"+"+nb3+"="+sum);
boolean validResponse = false;
while(!validResponse) {
System.out.println("Do you want to continue ? y/n");
String response = sc.next();
if(response.equals("n")) {
System.out.println("Thank you! see you next time :)");
playAgain = false;
validResponse = true;
} else if(response.equals("y")) {
playAgain = true;
validResponse = true;
} else {
System.out.println("Sorry, I didn't get it!");
}
}
}
}
New to Java and learning how to use While loops and random generator. This prints a multiplication question. Every time the user answers a question wrong, it should print the same question. Instead, it exits the program. What should I do?
while (true) {
Random multiply = new Random();
int num1 = multiply.nextInt(15);
int num2 = multiply.nextInt(15);
int output = num1 * num2;
System.out.println("What is the answer to " + num1 + " * " + num2);
Scanner input = new Scanner(System.in);
int answer = input.nextInt();
if (answer == output) {
if (answer != -1)
System.out.println("Very good!");
} else {
System.out.println("That is incorrect, please try again.");
}
}
If you want to repeat the same question when the user gets the answer wrong, you should use another while inside your main loop.
This inner loop continues to ask as long as you give a wrong answer.
I also replaced nextInt with nextLine, which reads in a whole line of text. This consumes the "Enter" key and is a safer approach at reading from the console. Since the result is now a String you need to use Integer.parseInt to convert it to an int. This throws an exception if you enter anything but a whole number so I wrapped it into a try-catch block.
If you want, you can add an additional check for validating user input. So in case the user wants to stop playing they only need to input "exit" and the whole outer loop will exit.
boolean running = true; // This flag tracks if the program should be running.
while (running) {
Random multiply = new Random();
int num1 = multiply.nextInt(15);
int num2 = multiply.nextInt(15);
int output = num1 * num2;
boolean isCorrect = false; // This flag tracks, if the answer is correct
while (!isCorrect) {
System.out.println("What is the answer to " + num1 + " * " + num2);
Scanner input = new Scanner(System.in);
try {
String userInput = input.nextLine(); // Better use nextLine to consume the "Enter" key.
// If the user wants to stop
if (userInput.equals("exit")) {
running = false; // Don't run program any more
break;
}
int answer = Integer.parseInt(userInput);
if (answer == output) {
if (answer != -1) {
System.out.println("Very good!");
isCorrect = true; // Set the flag to true, to break out of the inner loop
}
} else {
System.out.println("That is incorrect, please try again.");
}
}
catch(NumberFormatException e) {
System.out.println("Please enter only whole numbers");
}
}
}
Avoid while true. Declare a variable to true, pass the variable to the condición loop and set it to false when the answer is incorrect. You can use break too, but is easier to read the code when you use a exit condition in the while. Also read more about loops https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
The program asks for the user input for the double num 1 and double num 2
and if there is an exception I want it to ask again for the input of num 1 and num 2
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
double num1, num2;
int error = 0;
int text;
System.out.print("Enter 4 ");
text = sc.nextInt();
do{
try{
if(text == 4){
System.out.print("Enter number 1: ");
num1 = sc.nextDouble();
System.out.print("Enter number 2: ");
num2 = sc.nextDouble();
double quotient = num1/num2;
System.out.println("The Quotient of "+num1 + "/" +num2+ " = "+quotient);
}
}catch(Exception ex){
System.out.println("You've entered wrong input");
error = 1;
}
}while(error == 1);
}
then when I try the code if it will catch the exceptions by inputing string in the num1 or num 2 I'm having this infinite loop :
Enter number 1: You've entered wrong input
Enter number 1: You've entered wrong input
Enter number 1: You've entered wrong input
Enter number 1: You've entered wrong input
Enter number 1: You've entered wrong input
You need to reset the error variable inside the loop
do {
error = 0;
//...
} while(error == 1);
It is not necessary to utilize exception handling. Just use Scanner.hasNextDouble() method to find out if actual user input is double, otherwise continue the cycle.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double num1, num2;
num1 = readDouble(1, sc);
num2 = readDouble(2, sc);
double quotient = num1/num2;
System.out.println("The Quotient of " + num1 + "/" + num2 + " = " + quotient);
}
private static double readDouble(int i, Scanner sc) {
while (true) {
System.out.print("Enter number " + i + ": ");
if (!sc.hasNextDouble()) {
System.out.println("You've entered wrong input");
sc.next();
continue;
}
break;
}
return sc.nextDouble();
}
}
Its in C# but relatively similar :)
public class Program
{
private static double ReadUserInput (string message)
{
// This is a double
// The '?' makes it nullable which is easier to work with
double? input = null;
do
{
// Write message out
Console.Write(message);
// Read answer
var inputString = Console.ReadLine();
// Temp variable for the number
double outputNumber = 0;
// Try parse the number
if (double.TryParse(inputString, out outputNumber))
{
// The number was parsable as a double so lets set the input variable
input = outputNumber;
}
else
{
// Tell the user the number was invalid
Console.WriteLine("Sorry bud, but '" + inputString + "' is not a valid double");
}
}
while (input == null); // Keep running until the input variable is actually set by the above
// Return the output
return (double)input;
}
public static void Main()
{
// Read a number
var num1 = ReadUserInput("Enter number 1:");
// Read another number
var num2 = ReadUserInput("Enter number 2:");
// Show the calculation
Console.WriteLine("Answer: " + (num1*num2));
}
}
Demo
And for the actual code (in JAVA):
public class JavaFiddle
{
public static void main (String[] args)
{
// Read a number
Double num1 = ReadUserInput("Enter number 1:");
// Read another number
Double num2 = ReadUserInput("Enter number 2:");
// Show the calculation
System.out.println("Answer: " + (num1*num2));
}
public static Double ReadUserInput (String message)
{
java.util.Scanner inputScanner = new java.util.Scanner(System.in);
Double input = null;
do
{
// Write message out
System.out.println(message);
// Read answer
String inputString = inputScanner.nextLine();
try
{
// Try parse the number
input = Double.parseDouble(inputString);
}
catch (NumberFormatException e)
{
// Tell the user the number was invalid
System.out.println("Sorry bud, but '" + inputString + "' is not a valid double");
}
}
while (input == null); // Keep running until the input variable is actually set by the above
// Return the output
return input;
}
}
You probably want to test if there is no error:
}while(error != 1);
or
}while(error == 0);
You'll need a method for the input which calls itself, if the input is invalid.
double getInput(Scanner sc) {
try {
double num = sc.nextDouble();
return num;
} catch(Exception ex) {
System.out.println("You've entered wrong input");
return getInput(sc);
}
}
And call this method twice in your other method.
it may look ugly , but here is a way to do it
do
{
if(...)
{
boolean successReading = false;
while(!successReading)
{
try
{
System.out.print("Enter number 1: ");
num1 = sc.nextDouble();
System.out.print("Enter number 2: ");
num2 = sc.nextDouble();
successReading = true;
double product = num1*num2;
}
catch(Exception e)
{
successReading = false;
}
}
}
}while(...)
You need to add sc.next(); inside catch block.
nextDouble method doesn't clear buffer in case of exception. So next time you invoke it you get same error because old input is still in buffer.
Also you need to reset your error flag in the beginning of the loop.
You have to put sc.next(); in the catch so it will clear your scanner variable and it will ask for an input
This question already has answers here:
What's the best way to check if a String represents an integer in Java?
(40 answers)
Closed 8 years ago.
import java.util.Scanner;
public class test {
/**
* #param args
*/
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
boolean US1 = false;
boolean game;
int score = 1;
int wage = 0;
int fin_score = 0;
String ans;
if (US1 == false) {
game = false;
System.out.println (score);
System.out.println("Enter a wager");
wage = input.nextInt();
}
if (wage < score) {
System.out.println ("What is the capital of Liberia?");
ans = input.next();
if (ans.equalsIgnoreCase("Monrovia")) {
System.out.println ("You got it right!");
System.out.println ("Final score " + fin_score);
}
}
}
}
I have found a bunch of solutions using InputMismatchException and try{}catch{} but they never work when they are implemented in my code. is there a way to implement these here? I am trying to make a loop that iterates until the wage entered is an integer
You can have multiple catch exceptions in your code to check for bad input. For example
try{
wage = input.nextInt();
catch (InputMismatchException e){
System.out.print(e.getMessage());
//handle mismatch input exception
}
catch (NumberFormatException e) {
System.out.print(e.getMessage());
//handle NFE
}
catch (Exception e) {
System.out.print(e.getMessage());
//last ditch case
}
Any of these would work fine for Scanner errors, but InputMismatchException is the best to use. It would help your case a great deal if you included the non-working code with the try-catch blocks.
First of all, You should be using Scanner.nextLine, because Scanner.nextInt uses spaces and newlines as delimiters, which is probably not what you want (any thing after a space will be left on the scanner, breaking any next reads).
Try this instead:
boolean valid = false;
System.out.print("Enter a wager: "); //Looks nicer when the input is put right next to the label
while(!valid)
try {
wage = Integer.valueOf(input.nextLine());
valid = true;
} catch (NumberFormatException e) {
System.out.print("That's not a valid number! Enter a wager: ");
}
}
Yes! There is a good way to do this:
Scanner input = new Scanner(System.in);
boolean gotAnInt = false;
while(!gotAnInt){
System.out.println("Enter int: ");
if(input.hasNextInt()){
int theInt = input.nextInt();
gotAnInt = true;
}else{
input.next();
}
}
I don't understand the logic to this. If I run this code and enter a non-int such as the letter f, I get stuck in an infinite loop outputting the two println's and I am not given another chance to input an int to the scanner...it just keeps spitting out words to the console.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);//<<<<<SCANNER HERE
int opponents = 0;
boolean opponentsCreated = false;
while(opponentsCreated == false)
{
try
{
System.out.print("How many players: ");
int tempOpponents = scan.nextInt();
if(tempOpponents > 0)
{
opponents = tempOpponents;
opponentsCreated = true;
}
}
catch(InputMismatchException notAValidInt)
{
System.out.println("Not valid - must be a number greater than 0 ");
}
}
}
But if I simply change the Scanner to be declared inside the while loop, all of a sudden the program works as expected:
public static void main(String[] args) {
int opponents = 0;
boolean opponentsCreated = false;
while(opponentsCreated == false)
{
Scanner scan = new Scanner(System.in);//<<<<<SCANNER HERE
try
{
System.out.print("How many players: ");
int tempOpponents = scan.nextInt();
if(tempOpponents > 0)
{
opponents = tempOpponents;
opponentsCreated = true;
}
}
catch(InputMismatchException notAValidInt)
{
System.out.println("Not valid - must be a number greater than 0 ");
}
}
}
I honestly just sat here for 2 hours trying to figure out what the heck was wrong with my program only to find out it was a matter of where I declared my Scanner even though in both versions of the code the Scanner was not out of scope. So now I'm really curious why it works this way
Adding on to #HovercraftFullOfEels answer:
The root cause is, the scanner position does not move in case of the said exception. So scanner keeps reating same bad input again and again. Quoting JavaDoc
If the translation is successful, the scanner advances past the input
that matched.
catch(InputMismatchException notAValidInt)
{
scan.reset();
System.out.println("Not valid - must be a number greater than 0 ");
//position is still 0
scan.next(); //position is now 1
}
To visualize:
Input: f______________
Scanner position: ^______________
InputMismatchException ^______________
scan.next() _^_____________
Relevant source (look at the source comment):
try {
String s = next(integerPattern());
if (matcher.group(SIMPLE_GROUP_INDEX) == null)
s = processIntegerToken(s);
return Integer.parseInt(s, radix);
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
One possible problem is that you may be leaving the end of line token hanging when an excpetion occurs. If you handle this by making sure to swallow the end of line token when needed, you are likely OK. For example:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);// <<<<<SCANNER HERE
int opponents = 0;
boolean opponentsCreated = false;
while (opponentsCreated == false) {
try {
System.out.print("How many players: ");
int tempOpponents = scan.nextInt();
// line below corrected!
scan.nextLine(); // *** this might not be a bad idea either ***
if (tempOpponents > 0) {
opponents = tempOpponents;
opponentsCreated = true;
}
} catch (InputMismatchException notAValidInt) {
System.out.println("Not valid - must be a number greater than 0 ");
scan.nextLine(); // ****** this is what you need here *****
}
}
}
Nice question, by the way!