我正在尝试构建一个基本游戏,测试用户对州首府的了解。在这个阶段,我只是尝试为按钮设置一些基本功能。
我正在尝试获取它,以便当用户输入与正确答案相对应的字符串时,程序会显示“正确!”。我试过使用 IF ELSE 语句,但即使我输入正确的答案,它也会输出“错误!”。这可能很简单,但我无法发现它。如果有人能指出我正确的方向,将不胜感激。我是一个初学者,所以也许这完全是错误的方法,但这是我到目前为止所拥有的:
public class Main {
public static void main(String[] args){
Gui a = new Gui();
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Gui extends JFrame{
private static final long serialVersionUID = 1L;
JPanel row1 = new JPanel();
JLabel instructions = new JLabel("What is the capital of Alabama?");
JPanel row2 = new JPanel();
JLabel aLabel = new JLabel("Answer: ");
JTextField aField = new JTextField(14);
JPanel row3 = new JPanel();
JButton submit = new JButton("Submit");
JButton reset = new JButton("Reset");
public Gui() {
super("State Capitals Game");
setLookAndFeel();
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.insets = new Insets(5,5,5,5);
gc.gridx = 0;
gc.gridy = 0;
add(instructions, gc);
gc.gridx = 0;
gc.gridy = 1;
add(aLabel, gc);
gc.gridx = 0;
gc.gridy = 2;
add(aField, gc);
gc.gridwidth = 3;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.gridx = 0;
gc.gridy = 4;
add(submit, gc);
///this is where I'm stuck////
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String userIP = aField.getText();
String mg = "Montgomery";
if(userIP == mg){
System.out.println("correct!");
}else{
System.out.println("WRONG!");
}
}
});
gc.gridwidth = 3;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.gridx = 0;
gc.gridy = 5;
add(reset, gc);
reset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
reset.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "pressed");
aField.setText("");
}
});
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
// ignore error
}
}
}
最佳答案
当比较字符串时,你应该使用 equals() 方法:
String mg = "Montgomery";
if(userIP.equalsIgnoreCase(mg)){ // like this
System.out.println("correct!");
}else{
System.out.println("WRONG!");
}
否则你不会比较字符串的内容,而是比较不是你想要的引用
编辑:
实际上,您可能想要的是使用 equalsIgnoreCase()
,否则如果用户输入“montgomery”,它将抛出一个 false,因为 equals 区分大小写。你可以找到 api here
关于java - JAVA 中 ActionPerformed 方法中的 IF 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9837034/