I want the program to run only if it recieves 'y','Y','N' or 'n'. It doesn't work for other characters . However when user writes a more than 1 letter word with y or n (for e.g yddh,ndhdh, etc), the program still runs. please suggest what I can do. I tried taking 'a' as String but in if-else statement it showed error because string cannot be compared to char with == operator.
import java.util.Scanner;
class Main {
static char a;
public static void main(String[] args) {
System.out.println("Do you want to play this quiz?");
System.out.println("Type 'Y'for Yes or 'N' for no. It's case Insensitive.");
Scanner sc=new Scanner(System.in);
a=sc.next().trim().charAt(0);
if (a=='n'||a=='N')
{System.out.println("Thanks for downloading!");
System.exit(0);}
else if ((a !='n'&&a !='N') && (a !='y'&& a !='Y'))
{System.out.println("Invalid Syntax");
System.exit(0);}
else if(a=='y'||a=='Y')
{System.out.println("Welcome to the quiz");}
}
}
Aucun commentaire:
Enregistrer un commentaire