samedi 19 octobre 2019

Java:If user type 'y'||'Y' quiz begins,'n'||'N' quiz end.For rest,it shows invalid. I want to show invalid when user type word starting with y or n

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