import java.awt.EventQueue;
import java.awt.Window;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class batsmen {
private JFrame frame;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
batsmen window = new batsmen();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public batsmen() {
initialize();
}
/**
* Initialise the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblClue = new JLabel("Clue 1:");
lblClue.setBounds(20, 6, 61, 16);
frame.getContentPane().add(lblClue);
JLabel lblNewLabel = new JLabel("He is the leading international run scorer of all time");
lblNewLabel.setBounds(48, 30, 375, 16);
frame.getContentPane().add(lblNewLabel);
JLabel lblClue_1 = new JLabel("Clue 2");
lblClue_1.setBounds(20, 69, 61, 16);
frame.getContentPane().add(lblClue_1);
JLabel lblHePlayedFor = new JLabel("He played for India");
lblHePlayedFor.setBounds(48, 94, 375, 16);
frame.getContentPane().add(lblHePlayedFor);
JLabel label = new JLabel("");
label.setBounds(20, 229, 403, 16);
frame.getContentPane().add(label);
frame.setVisible(true);
textField = new JTextField();
textField.setBounds(20, 191, 290, 26);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblTakeAGuess = new JLabel("Take a Guess:");
lblTakeAGuess.setBounds(20, 163, 119, 16);
frame.getContentPane().add(lblTakeAGuess);
JButton btnNewButton = new JButton("Enter");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String answer = textField.getText();
answer = answer.toLowerCase();
if (answer == "sachin tendulkar") {
label.setText("Correct");
}else if (answer != "sachin tendulkar"){
label.setText("Incorrect. The answer was Sachin Tendulkar");
}
}
});
btnNewButton.setBounds(322, 191, 117, 29);
frame.getContentPane().add(btnNewButton);
}
}
Оператор if, похоже, не работает, так как даже если введен правильный ответ, он отображает «Неверно. Ответ был Сачин Тендулкар». Буду признателен за любую помощь. Я проверил, и ответ String содержит правильный ответ, но программа выводит «Неверно!». Это очень сбивает с толку и раздражает. Еще раз, я был бы признателен за любую помощь, которую вы можете дать мне. Спасибо




Вы могли бы попробовать
if (answer.equals("sachin tendulkar")) {
label.setText("Correct");
}
Обычно лучше использовать .equals() для сравнения строк. Вы можете прочитать, почему это здесь
Спасибо огромное. Это работает сейчас
но... нет оператора if