user1364808
user1364808

Reputation: 3

Error Comparing Strings in If Statement

I have a variable called "name" stored in another class in the working folder. I want to compare it to a user-input from a JOptionPane. The code I have is this:

String userInput = JOptionPane.showInputDialog(null, "What is the value?");
if(name.equals(userInput)){JOptionPane.showMessageDialog(null, "You are correct.");}

When I compile the program, it throws up the error that it cannot find symbol "name". Do I have to call the variable some other way in order to compare it to the user-input or am I totally wrong here?

Upvotes: 0

Views: 118

Answers (2)

Azodious
Azodious

Reputation: 13872

Lets say in working folder you have following two class:

class IHaveNameVariable
{
    String name;
}

class IAccessNameVariable
{
    public void someMethod()
    {
        // Uncomment the code below
        // and it will compile.

        // IHaveNameVariable aRef = new IHaveNameVariable();

        String userInput = JOptionPane.showInputDialog(null, "What is the value?");
        if(/*aRef.*/name.equals(userInput))
        {
            JOptionPane.showMessageDialog(null, "You are correct.");
        }
    }
}

So, that's how you access a field of another class. if the field is static, no need to create object using new; simply use the class name.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272537

If name is a member of a different object, then you will need to specify which object.

thingWithAName.name.equals(userInput)

Upvotes: 1

Related Questions