Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I frequently face "Cannot find symbol", how to avoid it?

import java.util.Scanner;

public class MainFile {
    public static void main(String[] args) {    
        do {
            Scanner asc = new Scanner(System.in);
            String userTXT = asc.nextLine();
        } while(userTXT != "Twitter!");     
    }
}

The code is simple. Yet, there’s Cannot find symbol for userTXT.
Any tip to avoid such Error is welcomed!

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It’s because you haven’t defined or initialised userTXT in a scope that can be seen from within the while loop.

You have defined it within the scope of the while loop which can’t see variables defined inside it as the while loop and the variable are not in the same scope ({}).

Maybe try this:

import java.util.Scanner;

public class MainFile {
    public static void main(String[] args) {
        String userTXT = ""; // define it here (not necessarily with "" though)
        do {
            Scanner asc = new Scanner(System.in);
            userTXT = asc.nextLine();
        } while(!userTXT.equals("Twitter!"));
    }
}

Also you should use .equals() instead of != when comparing Strings in Java.

Hope this helps!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading