[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');
}
}