错误比较If语句中的字符串

时间:2012-04-29 23:40:08

标签: java if-statement compiler-errors user-input

我有一个名为“name”的变量存储在工作文件夹的另一个类中。我想将它与JOptionPane的用户输入进行比较。我的代码就是:

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

当我编译程序时,它会抛出无法找到符号“name”的错误。我是否必须以其他方式调用变量才能将其与用户输入进行比较,或者我在这里完全错了?

2 个答案:

答案 0 :(得分:1)

如果name是其他对象的成员,则需要指定哪个对象。

thingWithAName.name.equals(userInput)

答案 1 :(得分:0)

让我们说在工作文件夹中你有以下两个课程:

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.");
        }
    }
}

所以,这就是你如何访问另一个类的字段。如果字段为static,则无需使用new创建对象;只需使用类名。

相关问题