2012-04-29 65 views
0

我有一个名为“name”的变量存储在工作文件夹中的另一个类中。我想将它与来自JOptionPane的用户输入进行比较。我的代码是这样的:比较If语句中的字符串时出错

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

当我编译程序时,它抛出了错误,它无法找到符号“名”。我是否需要以其他方式调用变量以便将其与用户输入进行比较,还是我在这里完全错误?

回答

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创建对象;只需使用类名。

1

如果name是不同对象的成员,那么您将需要指定哪个对象。

thingWithAName.name.equals(userInput) 
+0

首选样式是使用“访问器”方法,而不是直接抓取名称。例如'if(thingWithAName.getName()。equals(userInput))//在这里做某事' – user949300