infinite loop when trying to restart after try catch [duplicate] - java

This question already has answers here:
try/catch with InputMismatchException creates infinite loop [duplicate]
(7 answers)
Closed 7 years ago.
[SOLVED] By adding console.next(); to my catch statement.
catch(InputMismatchException fe) {
System.out.println("You didnt enter an integer. Try again");
restart = 'y';
console.next();
}}
while(restart=='y');
}}
[Solution]^^^^^^
static public char restart;
public static void main(String[] args) {
do {
try {
int num1, num2, check, sum = 0, count = 1, sqsum = 0;
do {
System.out.println("Please enter a number");
num1 = console.nextInt();
Here is where i have set restart as public so i can use it with the try catch in order to restart the program when a inputmissmatchexception happens
catch(InputMismatchException fe) {
System.out.println("You didnt enter an integer. Try again");
restart = 'y';
}}
while(restart=='y');
}}
and here is the catch where if it does catch the exception i set restart to y then if it is y then the do while would restart the program. But it doesn't it just asks the user to enter a number then displays my catch message "you didn't enter an integer....." I believe this means the scanner isn't searching for another value to place in the variable, but i have tried and don't know how to fix this.
FULL: This is a project for school where i have to have them enter two number and do things to them. It works and does everything its supposed to but i just would like to have the program restart if the user inputs a non integer.
package p321ex9;
import java.util.*;
public class p321ex9 {
static Scanner console = new Scanner(System.in);
static public char restart = 'n';
public static void main(String[] args) {
do {
try {
int num1, num2, check, sum = 0, count = 1, sqsum = 0;
do {
System.out.println("Please enter a number");
num1 = console.nextInt();
System.out.println("Please enter a second number that is grester than the first number you entered which "
+ "was " + num1 + ".");
num2 = console.nextInt();
if (num1 > num2) {
System.out.println("the first number was greater than your second number, please enter new numbers and "
+ "make sure the second is greater.");
}
}
while (num1 > num2);
System.out.println("List of odd numbers between the first and second numbers you entered inclusive:");
while (num1 <= num2) {
check = (num1 % 2);
if (check == 1) {
sqsum += (num1 * num1);
System.out.print(num1 + " ");
} else {
sum += num1;
}
num1++;
}
System.out.println();
System.out.println("The sum of all even numbers the first and second numbers you entered inclusive"
+ ": " + sum);
System.out.println("Sum of the squares of all the odd numbers between your two entered numbers inclusive: " + sqsum);
System.out.println("All numbers from 1 to 10 squared");
while (count <= 10) {
System.out.print(count + " squared = " + (count * count) + " ");
count++;
}
} catch (InputMismatchException fe) {
System.out.println("You didnt enter an integer. Try again");
restart = 'y';
}
}
while (restart == 'y');
}
}

because when you set restart='y', you did not reset it when user enter valid input (integer)
Better way of doing this:
public static void main (String[] args){
Scanner console=new Scanner(System.in);
int num1,num2,check,sum=0,count=1,sqsum=0;
do{
System.out.println("Please enter a number");
String input=console.nextLine();
if(input.replaceAll("\\d","").length()==0){
num=Integer.parseInt(input);
restart='n';
}
else{
System.out.println("You didnt enter an integer. Try again");
restart='y';
}
}
while (restart=='y');
}

Related

How do I make a for loop ask a user for the same input again after an Exception?

So to clarify, when the program asks the user for number 1: if the user were to input a letter, I need the program to tell the user that there was an input mismatch, then ask the user for number 1 again. This needs to be achieved using only one single for loop, and there can be no negative numbers that affect the sum or the average. Here's what I have so far:
import java.util.*;
import java.text.*;
class fivePositiveNumbers{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int userNumber;
int sum = 0;
System.out.println("This program will give the sum and average of 5 positive integers,");
for(int i = 1; i <= 5; i++){
System.out.println("Enter number " + i + ": ");
try{
userNumber = keyboard.nextInt();
sum = sum + userNumber;
if(userNumber <= 0){
throw new Exception("The integer must be positive.");
}
} catch(InputMismatchException e){
System.out.println("This data type is incorrect.");
keyboard.nextLine();
} catch(Exception e){
System.out.println(e.getMessage());
keyboard.nextLine();
}
}
System.out.println("The sum is " + sum + " and the average of your 5 numbers is " + sum / 5 + ".");
}
}
Use a while or a for loop that will increment the loop count ONLY IF a valid input is provided. Your solution increments the loop counter automatically regardless of the validity of the input.
int i = 1;
while (i <= 5) {
System.out.println("Enter number " + i + ": ");
try{
userNumber = keyboard.nextInt();
if(userNumber <= 0){
throw new Exception("The integer must be positive.");
}
sum = sum + userNumber; // this belongs after the negative check
i++; // increment the count after all validations are successfully completed
} catch(InputMismatchException e){
System.out.println("This data type is incorrect.");
keyboard.nextLine();
} catch(Exception e){
System.out.println(e.getMessage());
keyboard.nextLine();
}
}
}
If you choose to use a for loop, remove the counter increment out of the loop declaration
for (int i = 1; i <= 5;) {
// your logic and exception handling here
i++; // as in the while, increment only after all validations are successfully completed
}
Another point... I don't think it is necessary to throw an exception if the number is negative. I think it is better to simply execute a continue to avoid incrementing the loop counter. This is the result of this:
This program will give the sum and average of 5 positive integers,
Enter number 1:
-5
The integer must be positive.
Enter number 1:
-2
The integer must be positive.
Enter number 1:
-3
The integer must be positive.
Enter number 1:
-4
The integer must be positive.
Enter number 1:
-5
The integer must be positive.
Enter number 1:
1
Enter number 2:
2
Enter number 3:
3
Enter number 4:
5
Enter number 5:
4
The sum is 15 and the average of your 5 numbers is 3.
As you can see, I entered several negative numbers and the program continued to run without incrementing the loop counter. The complete solution with continue:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int userNumber;
int sum = 0;
System.out.println("This program will give the sum and average of 5 positive integers,");
for(int i = 1; i <= 5; ){
System.out.println("Enter number " + i + ": ");
try{
userNumber = keyboard.nextInt();
if(userNumber <= 0){
System.err.println("The integer must be positive.");
continue;
}
sum = sum + userNumber;
i++;
} catch(InputMismatchException e){
System.out.println("This data type is incorrect.");
keyboard.nextLine();
} catch(Exception e){
System.out.println(e.getMessage());
keyboard.nextLine();
}
}
System.out.println("The sum is " + sum + " and the average of your 5 numbers is " + sum / 5 + ".");
}
class fivePositiveNumbers{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int userNumber;
int sum = 0;
System.out.println("This program will give the sum and average of 5 positive integers,");
int ctr = 0;
for(;;){
System.out.println("Enter number " + (ctr+1) + ": ");
try{
userNumber = keyboard.nextInt();
if(userNumber <= 0){
throw new Exception("The integer must be positive.");
}
sum = sum + userNumber;
ctr++;
} catch(InputMismatchException e){
System.out.println("This data type is incorrect.");
keyboard.nextLine();
} catch(Exception e){
System.out.println(e.getMessage());
keyboard.nextLine();
}
if (ctr == 5) break;
}
System.out.println("The sum is " + sum + " and the average of your 5 numbers is " + sum / 5 + ".");
}
}

Cant get my integers to add to get correct output

so I am trying to do my homework, this being the question:
Write a program that prompts the user to read two integers and displays their sum. If anything but an integer is passed as input, your program should catch the InputMismatchException that is thrown and prompt the user to input another number by printing "Please enter an integer."
Below is the sample run and what I am supposed to test.
SAMPLE RUN #1: java InputMismatch
Enter an integer: 2.5↵
Please enter an integer↵
Enter an integer: 4.6↵
Please enter an integer↵
Enter an integer: hello!↵
Please enter an integer↵
Enter an integer:7↵
Enter an integer:5.6↵
Please enter an integer↵
Enter an integer:9.4↵
Please enter an integer ↵
Enter an integer:10↵
17↵
When I am testing my code and putting in the integers, it works as it is supposed to, however, I am stuck on getting the integers to add together when both inputs are entered correctly. What am I doing wrong?
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("The number entered is " + number);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
System.out.println((num1 + num2));
}
}
try adding another condition to your while and putting the numbers in an array.
int[] numbers = new int[2];
and change this in your while loop:
int count = 0;
while (!isValid && count <2) {
try {
System.out.print("Enter an integer: ");
numbers[count] = input.nextInt();
count++;
System.out.println("The number entered is " + number);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
Hope that helped.
Check with this approach:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[2];
int count = 0;
while (count <= 1) {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("The number entered is " + number);
numArray[count] = number;
count++;
} catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
int num1 = numArray[0];
int num2 = numArray[1];
System.out.println((num1 + num2));
}
You need to stitch together the logic. As you are taking 2 numbers 2 flags will ensure you got correct input for both variables. Also both flags ensure you are taking input correctly for num1 or num2 when an exception occurs.
If you need to input n arbitrary integers, then you may want to use dynamic collections and add numbers to collection.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean num1Valid = false;
boolean num2Valid = false;
while (num1Valid==false || num2Valid==false) {
try {
if(num1Valid == false) {
System.out.print("Enter an integer for num1: ");
num1 = input.nextInt();
System.out.println("The number entered for num1 is " + num1);
num1Valid = true;
}
if(num2Valid == false) {
System.out.print("Enter an integer for num2: ");
num2 = input.nextInt();
System.out.println("The number entered for num2 is " + num2);
num2Valid = true;
}
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
input.close()
System.out.println((num1 + num2));
}
You need capture the exception, in this case you can using e.getMessage()
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1=0, number=0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
number = input.nextInt();
if(number > 0) {
System.out.println("The number entered is " + number);
}
num1 += number;
System.out.println("are would you like continue the program? Y or
N ");
String condition = input.next();
if(condition.equalsIgnoreCase("Y")) {
isValid = false;
} else {
isValid = true;
}
}
catch (InputMismatchException ex) {
System.out.println(ex.getMessage());
System.out.println("You cannot type words");
isValid = true;
}
}
System.out.println("Result = " + num1);
input.close();
}
}
in another case do you can use the method matches using expression language
saw example below:
if(valor.matches("[0-9]*"))
You can add the two numbers inside the try block
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
num1 = input.nextInt();
System.out.print("Enter an integer: ");
num2 = input.nextInt();
System.out.println("The numbers you entered are " + num1 + ","+num2);
int sum = num1+num2;
System.out.println("The sum Of the numbers you entered is: "+ sum);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
System.out.println((num1 + num2));
}
}
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[2];
int count = 0;
while (count <= 1) {
try {
System.out.print("Enter an integer:");
int number = input.nextInt();
numArray[count] = number;
count++;
} catch (InputMismatchException e) {
System.out.println("Please enter an integer.");
input.nextLine();
}
}
System.out.println(numArray[0] + numArray[1]);
}
}

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 print error message when user enters anything that is not a double?

I am trying to create a Java program that reads a double value from the user, Printing the difference between these two numbers so that the difference is always positive. I need to display an Error message if anything other than a number is entered. Please help, thank you !!
When I run the program and enter the second double value nothing happens. I have also tried adding try and catch but I get errors saying num1 cannot be resolved to a variable :(
import java.util.Scanner;
public class Positive {
public static void main(String[] args) {
//Reads input
Scanner sc = new Scanner(System.in);
System.out.println ("Please enter a double vaule: ");
double num1 = Math.abs(sc.nextDouble());
System.out.println("Please enter a second double vaule: " );
double num2 = Math.abs(sc.nextDouble());
double total = 0;
double total2 = 0;
if (sc.hasNextDouble()) {
num1 = sc.nextDouble();
if (num1>num2) {
total = ((num1 - num2));
System.out.println("The difference is " + total);
}
if ((num1 < num2)); {
total2 = ((num2 - num1));
System.out.println("The difference is "+ total2);
}
}else {
System.out.println("Wrong vaule entered");
}
}
}
You have the right idea. You just need to remove the semicolon (;) after the last if and properly nest your conditions:
if (sc.hasNextDouble()) {
num1 = sc.nextDouble();
if (num1 > num2) {
total = (num1 - num2);
System.out.println("The difference is " + total);
}
else if (num1 < num2) {
total2 = (num2 - num1);
System.out.println("The difference is "+ total2);
}
} else {
System.out.println("Wrong vaule entered");
}
Try running your code and when you enter your first double, type in something random like "abc". What happens? In your console it should display an error named java.util.InputMismatchException. You can use a try catch block like so:
try {
//tries to get num1 and num2
double num1 = Math.abs(sc.nextDouble());
double num2 = Math.abs(sc.nextDouble());
} catch (java.util.InputMismatchException i){
//will only go here if either num1 or num2 isn't a double
System.out.println("error");
}
Basically, the code will try to get num1 and num2. However if you enter a non-double, it'll "catch" the java.util.InputMismatchException and go to the catchblock
I might've misinterpreted your question, but if you want to find the absolute value of the difference between num1 and num2, all you have to do is:
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Please enter a double value: ");
double num1 = sc.nextDouble();
System.out.println("Please enter a double value: ");
double num2 = sc.nextDouble();
System.out.println("The difference is: " + Math.abs(num1 - num2));
} catch (java.util.InputMismatchException i) {
System.out.println("error");
}
}
}
To show error message until the user enters a double value I used a while loop for each value (num1 and num2).
If user enters a wrong value "Wrong vaule entered, Please enter again: " message will show and waits for the next input sc.next();
If user enters a double value check will be false and exits while loop
import java.util.Scanner;
public class Positive {
public static void main(String[] args) {
// Reads input
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a double vaule: ");
double num1 = 0;
double num2 = 0;
double total = 0;
double total2 = 0;
boolean check = true;
while (check) {
if (sc.hasNextDouble()) {
num1 = Math.abs(sc.nextDouble());
check = false;
} else {
System.out.println("Wrong vaule entered, Please enter again: ");
sc.next();
}
}
check = true; // that's for second control
System.out.println("Please enter a second double vaule: ");
while (check) {
if (sc.hasNextDouble()) {
num2 = Math.abs(sc.nextDouble());
check = false;
} else {
System.out.println("Wrong vaule entered, Please enter again: ");
sc.next();
}
}
if (num1 > num2) {
total = ((num1 - num2));
System.out.println("The difference is " + total);
} else if ((num1 < num2)) {
total2 = ((num2 - num1));
System.out.println("The difference is " + total2);
}
}
}

Looping for odd and even number in java

how do i repeatedly ask the user to enter an input until the user enters a negative number. If the user enters a negative number or 0, the program will end?
import java.util.Scanner;
public class OddEvenInt {
public static void main(String args[]) {
Scanner s = new Scanner(System. in );
int x;
do {
System.out.println("Enter an integer to check if it is odd or even ");
x = s.nextInt();
if (x % 2 == 0)
System.out.println("You entered an even number.");
else
System.out.println("You entered an odd number.");
} while (x % 2 == 0);
}
}
You gotta change the while clause :
while (x>0)
use < and >
public static void main(String[] arguments) {
Scanner s = new Scanner(System.in);
int x = 0;
do {
System.out.println("Enter an integer to check if it is odd or even ");
try {
x = Integer.parseInt(s.nextLine());
if (x > 0) {
System.out.println("You entered an even number.");
} else if (x == 0) {
System.out.println("You entered 0, thats not negativ or positiv.");
} else {
System.out.println("You entered an odd number.");
}
} catch (Exception e) {
//e.printStackTrace();
System.out.println("U call this an Integer? :P");
}
} while (x > 0);
return;
}
last edit: check if your input is numberic, if you want to check the error you can remove // from the catch-block

Categories

Resources