0

I've been attempting to create a menu using the 'do' feature in Java. I start by providing the user with a range of options, then I request the user to enter their option through the keyboard and in turn, creating the string variable 'selection'. However when I reference the 'selection' variable in my loop expression, the error indication appears with "selection cannot be resolved to a variable". Why is that so and how can I correct this?

Please refer to the code below.

do{
       //output presenting the user with options
        System.out.print("A simple Menu\n");
        System.out.print("Y - Yolk\n");
        System.out.print("N - Naan\n");
        System.out.print("X - Exit\n\n");

        //request user input using the import.util.*; feature
        System.out.print("Enter your selection: ");
        String selection=keyboard.nextLine();
        // So here the 'selection' string is made

       }
       //Now here, whatever the user has selected as an option will be 
       // passed through and more options will appear.
       while(selection!="X");

       //however I get prompted with the red squiggly line underneath the 
       //'selection' variable that seems to not recognize 'selection' as a string

1 Answers1

1

your selection variable is out of the scope (or you can think as already destroyed) when the loop trying to check it again. so define it outside the loop.

String selection ="";
        do{
           //output presenting the user with options
            System.out.print("A simple Menu\n");
            System.out.print("Y - Yolk\n");
            System.out.print("N - Naan\n");
            System.out.print("X - Exit\n\n");

            //request user input using the import.util.*; feature
            System.out.print("Enter your selection: ");
            selection=keyboard.nextLine();
            // So here the 'selection' string is made

           }
           //Now here, whatever the user has selected as an option will be 
           // passed through and more options will appear.
           while(!selection.equals("X"));

Edit

I totally agree with @ Tim Biegeleisen. But His error message is not about the String comparison with logical operator. anyway I edited my answer. Thank you very much for pointing out about it.

Shanil Fernando
  • 1,302
  • 11
  • 13
  • 1
    Logically compare strings using `String#equals()` _not_ `!=`. – Tim Biegeleisen Jul 01 '17 at 10:03
  • Thank you Shanil. by defining my variable 'selection' outside the do-while loop I now have been able to proceed with the program. I've also implemented '!selection.equals("X")' within the while expression. Many Thanks Tim! – Cristobal Contreras Jul 01 '17 at 10:09