I want write a program that shows menu and asks the user to select from two choices a) Find odd numbers : The program asks the user to enter integer number x, then prints the odd integers from x to 1 b) Find even numbers: The program asks the user to enter integer number x, then prints the even integers from x to 2. - Your code should recognize the invalid characters and display "invalid choice!!" message. - The program should display the message “Do you want to continue ? y or n “ after each calculation. The user will enter ‘y’ to continue, otherwise the user will enter 'n'. I wrote my code like this
import java.util.*;
public class choices{
//main method
public static void main(String args[]){
Scanner input=new Scanner(System.in);
String op;
int num;
String op2;
String odd="";
String even="";
int count=0;
do{
System.out.println("a) Find odd numbers");
System.out.println("b) Find even numbers");
System.out.print("choose an option [ a, b]: ");
op=input.next();
if (op.equals('a'))
System.out.print("Enter Integer number : ");
num=input.nextInt();
for(int i=num ; i >=num-i ;i--){
if(num%2!=0)
odd=odd+""+i;
System.out.print("odd numbers are : "+odd );
}
if (op.equals('b')){
for(int i=num ; i >=num-i ;i--){
if(num%2==0)
even=even+""+i;
System.out.print("even numbers are : "+even );
}
}
else
System.out.println("invalid choice");
System.out.print("Do you want to continue (y or n)?");
op2=input.next();
if(op2.equals('n'))
System.out.println("Bye");
}
while(!op2.equals('n'));
count++;
}
}
but the problem is : it stop after > choose an option [ a, b]: b
a) Find odd numbers
b) Find even numbers
choose an option [ a, b]: b
d
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at choices.main(choices.java:30)