简体   繁体   English

我在使用 JOptionPane 和 if/else 语句时遇到问题

[英]I am having Issues with JOptionPane and if/else statements

I am having trouble with JOptionPane.我在使用 JOptionPane 时遇到问题。 My program is supposed to ask the user a question, if they answer Y is moves on to the next question.我的程序应该问用户一个问题,如果他们回答 Y 则继续下一个问题。 But if they answer N it asks another question.但如果他们回答 N,它会问另一个问题。 My problem is when the user answers with N it just moves on to the Y question.我的问题是当用户用 N 回答时,它只是转到 Y 问题。 It is basically moving in the order the questions are asked and not following the parameters of the if-else statement.它基本上按照提问的顺序移动,而不是遵循 if-else 语句的参数。 Here is my code:这是我的代码:

   import javax.swing.JOptionPane;
    
    public class Helper2 {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            helpMe(); 
        }
        
        public static void helpMe(){
            String ans = JOptionPane.showInputDialog("Does you car turn over? (Y/N)"); 
            if (ans.equalsIgnoreCase("Y")){
                JOptionPane.showInputDialog("Does it run rough? (Y/N)"); 
                if (ans.equalsIgnoreCase("Y")){
                    JOptionPane.showInputDialog("Did you buy cheap gas (Y/N)");
                } else if (ans.equalsIgnoreCase("N")){
                    JOptionPane.showInputDialog("Does it stop poorly? (Y/N)");
                }
    
                
            }else if (ans.equalsIgnoreCase("N")) {
                JOptionPane.showMessageDialog(null, "Your battery is dead");
                
            }else {
                JOptionPane.showMessageDialog(null, "ERROR"); 
            }
            
            
        }
        }

You aren't changing the value of ans in every question.您不会在每个问题中更改ans的值。 Try something like this:尝试这样的事情:

import javax.swing.JOptionPane;

public class Helper2 {
    public static void main(String[] args) {
        helpMe();
    }

    public static void helpMe() {
        String ans = JOptionPane.showInputDialog("Does you car turn over? (Y/N)");
        if (ans.equalsIgnoreCase("Y")) {
            ans = JOptionPane.showInputDialog("Does it run rough? (Y/N)");
            if (ans.equalsIgnoreCase("Y")) {
                ans = JOptionPane.showInputDialog("Did you buy cheap gas (Y/N)");
            } else if (ans.equalsIgnoreCase("N")) {
                ans = JOptionPane.showInputDialog("Does it stop poorly? (Y/N)");
            }


        } else if (ans.equalsIgnoreCase("N")) {
            JOptionPane.showMessageDialog(null, "Your battery is dead");

        } else {
            JOptionPane.showMessageDialog(null, "ERROR");
        }
    }
}

Basically, I never redefined ans .基本上,我从未重新定义ans So I had to put ans = before all JOptionPane statements except for the last two.所以我不得不把ans =放在除了最后两个之外的所有JOptionPane语句之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM