簡體   English   中英

為什么我不能在我的 If 語句中檢查方法是否返回 true?

[英]Why can't I check if a method returns true in my If statement?

我想要實現的是我希望我的 if 語句檢查我的方法 verifyAnswer 是否返回 true,如果它返回 true,我希望它取消我的計時器。 因此,我搜索了如何執行以下操作,但我發現的答案都說了類似的話,但是我認為,由於我在該方法中的論點取決於用戶的答案,因此它不起作用。 這看起來很簡單,但我是 Java 的新手,似乎無法讓它工作。 謝謝大家的幫助!

public boolean verifyAnswer(String userAnswer) {
    
    
    String correctAnswer = this.questions.get(currentQuestionIndex).correctAnswerText;
    

    if(userAnswer.equals(correctAnswer)) {
        
        timer.pauseTimer();

        JOptionPane.showMessageDialog(null, "Correct Answer");
        return true;
    }
    else {
        timer.pauseTimer();
        JOptionPane.showMessageDialog(null, "Wrong Answer");
        return false;
    }
    
}    


Timer t = new Timer();
    
    int[] score = {0};
    TimerTask tt = new TimerTask() {
        @Override
        public void run() {
            System.out.println(++score[0]);
            if (score[0] == 30) {
                t.cancel();
                
            }
            else if(verifyAnswer()) { //Why doesn't this line work?
                t.cancel();
            }
        };
    };
    
    t.scheduleAtFixedRate(tt, 0, 1000);

下面是一個帶有動作偵聽器的 label,因此當用戶單擊它時,它會使用 verifyAnswer 方法檢查 label 中的文本,以查看用戶是否選擇正確。

    label_option_a = new JLabel("<html>Option A</html>");
        label_option_a.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent arg0) {
            
        verifyAnswer(label_option_a.getText());
        }
    });

因為您沒有在verifyAnswer方法中傳遞參數。 verifyAnswer期望字符串參數。

public boolean verifyAnswer(String userAnswer) { .. }

你應該這樣打電話

else if(verifyAnswer("pass_what_argument_you_want_to_pass_for_user_answer")) { 
     t.cancel();
}

您應該在方法中更改 true 和 false 返回。 像那樣

public boolean verifyAnswer(String userAnswer) {


String correctAnswer = this.questions.get(currentQuestionIndex).correctAnswerText;


if(userAnswer.equals(correctAnswer)) {
    
    timer.pauseTimer();

    JOptionPane.showMessageDialog(null, "Correct Answer");
    return false;
}
else {
    timer.pauseTimer();
    JOptionPane.showMessageDialog(null, "Wrong Answer");
    return true;
}

} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM