【问题标题】:If-else statements not working for modelif-else 语句不适用于模型
【发布时间】:2013-10-23 18:57:46
【问题描述】:

我想要什么

在 JPanel 上,我有一个 JButton 和一个 JTextArea。按下 JButton 后,必须在 JTextArea 内打印某些文本。该特定文本由 if-else 语句确定。 if-else 的条件是基于一个整数变量 R。

基本上它是我正在尝试进行的类似问答的调查。我使用 R 记录用户的答案。当用户点击一个选项时,R 的值会更新。

我使用字符串变量 yourphone。如果最后 R 的值是 120,那么你的手机会更新为一个字符串,例如。 Xperia Z。

我所说的最后一个 JPanel 是我显示结果的地方。在 if-else 语句中使用 R 的总值。

结构

我这样启动变量

int R=0;
String yourphone;

这是JPanel的代码

final JPanel result = new JPanel();
        result.setBackground(Color.BLACK);
        getContentPane().add(result, "name_17130054294139");
        result.setLayout(null);


        final JTextArea txtrphoneresult = new JTextArea();
        txtrphoneresult.setRows(5);
        txtrphoneresult.setBounds(68, 84, 285, 148);
        result.add(txtrphoneresult);

        JButton btnShowResult = new JButton("Show Result");
        btnShowResult.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                txtrphoneresult.setText(yourphone + R);

            }
        });
        btnShowResult.setBounds(68, 29, 103, 32);
        result.add(btnShowResult);

这是我的 if-else 语句的样子

if(R==1749)
        {
            yourphone = "Galaxy Mega 5.8";
        }
if(R==1726)
        {
            yourphone = "Xperia Z";
        }
else
            {
                    yourphone = "NO Result";
            }

问题

在执行时,无论结果如何,始终为“NO Result”,这意味着 R 的值始终与我的预测总数不同。但这不可能是正确的,因为我在旁边打印了 R 的值

txtrphoneresult.setText(yourphone + R);

结果输出是“NO Result 1749”。这是不可能的,因为它表明 R 的值已更新。如果它是 1749,那么输出应该是“Galaxy Mega 5.8”。我不知道为什么当 if 条件明确满足时,它会从 else 语句中获取您手机的输出。

【问题讨论】:

    标签: java swing if-statement


    【解决方案1】:

    你需要在第一个if之后添加else

    if(R==1749) {
        yourphone = "Galaxy Mega 5.8";
    } else if(R==1726) {
        yourphone = "Xperia Z";
    } else {
        yourphone = "NO Result";
    }
    

    否则,yourphone 将是 "NO Result",即使 R == 1749

    【讨论】:

    • 我试过了。它仍然无法正常工作。显示“无结果 1749”。
    • 你试过调试了吗?
    • 我在 Java 方面处于非常初级的水平。所以我不知道该怎么做。你能把我链接到有用的地方吗?
    • R的值在哪里设置?
    • 没关系,它已经解决了。我将 if else 语句放在了 JButton 的 ActionListener 中,然后砰!有效。谢谢
    【解决方案2】:
    if(R==1749)
      yourphone = "Galaxy Mega 5.8";
    else if(R==1726)
      yourphone = "Xperia Z";
    else
      yourphone = "NO Result";
    
    this will solve your problem;
    

    【讨论】:

      【解决方案3】:

      您的嵌套if-else 语句不正确。 If-else 条件应该是

      if(R==1749){
          yourphone = "Galaxy Mega 5.8";
      }
      else if(R==1726){
          yourphone = "Xperia Z";
      }
      else{
           yourphone = "NO Result";
      }
      

      【讨论】:

      • 我试过了。它仍然无法正常工作。显示“无结果 1749”
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 2021-08-26
      • 2022-01-25
      • 2013-12-25
      • 1970-01-01
      相关资源
      最近更新 更多