Java 比较If语句中的字符串时出错
我在工作文件夹的另一个类中存储了一个名为“name”的变量。我想将其与来自JOptionPane的用户输入进行比较。我的代码是:Java 比较If语句中的字符串时出错,java,if-statement,compiler-errors,user-input,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.");} 当我编译程序时,它抛出了一个错误,即它找不到符
String userInput = JOptionPane.showInputDialog(null, "What is the value?");
if(name.equals(userInput)){JOptionPane.showMessageDialog(null, "You are correct.");}
当我编译程序时,它抛出了一个错误,即它找不到符号“name”。我是否必须以其他方式调用变量以将其与用户输入进行比较,或者我在这里完全错了?如果
name
是其他对象的成员,则需要指定哪个对象
thingWithAName.name.equals(userInput)
假设在工作文件夹中有以下两个类:
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.");
}
}
}
这就是访问另一个类的字段的方式。如果字段是静态的,则无需使用新的创建对象;只需使用类名。首选样式是使用“访问器”方法,而不是直接获取名称。e、 g.if(thingWithAName.getName().equals(userInput))//在这里做些什么