basically what I am trying to do is:
Get the user to enter a 5 digit number. If all of the digits in the number are Odd, it will print out "All of the digits are odd" and if all of the digits are not Odd, then it will print out "Not all of the digits are odd", and then it will ask the user if they want to Enter a new Number by pressing Y or N and then it will ask them for another 5 digit number and repeat.
Here is my problem:
When a user does not enter a 5 digit number, E.G enters a string/character, then I want it to say "That was not a number, please try again", I tried to do this with try and catch, I can make it so it says try again, but I am unsure on how to make the code return back to the beginning after an error has been thrown. Sorry I am bad at java :-/ I also have this problem when user does not enter Y or N and enter a number.
code:
package veryoddnumber;
import java.util.*;
public class VeryOddNumber {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a 5 digit number...");
boolean yesno;
do {
try {
int number = scan.nextInt();
int length = String.valueOf(number).length();
if (length == 5) {
String digits = String.valueOf(number);
char number1 = digits.charAt(0);
char number2 = digits.charAt(1);
char number3 = digits.charAt(2);
char number4 = digits.charAt(3);
char number5 = digits.charAt(4);
if (number1 % 2 != 0 && number2 % 2 != 0 && number3 % 2 != 0 && number4 % 2 != 0 && number5 % 2 != 0) {
System.out.println("All of the numbers are odd...");
} else {
System.out.println("Not all of the numbers are odd...");
}
System.out.println("Would you like to enter another number? (Y/N)");
} else {
System.out.println("You did not enter a 5 digit number! Try again...");
System.out.println("Enter a 5 digit number...");
}
} catch (Exception e) {
System.out.println("That was not a number! Try again...");
}
try {
char letter = scan.next().charAt(0);
if (letter == 'Y' || letter == 'y') {
yesno = true;
} else if (letter == 'N' || letter == 'n') {
break;
} else {
System.out.println("I will take that as a no!");
break;
}
System.out.println("Enter a 5 digit number...");
} catch (Exception e) {
System.out.println("You did not enter a letter...");
}
} while (yesno = true);
System.out.println("Goodbye!");
}
}