0

我想要的是

在 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";
            }

问题

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

txtrphoneresult.setText(yourphone + R);

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

4

3 回答 3

6

如果出现以下情况,您需要先添加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

于 2013-10-23T10:54:21.057 回答
1
if(R==1749)
  yourphone = "Galaxy Mega 5.8";
else if(R==1726)
  yourphone = "Xperia Z";
else
  yourphone = "NO Result";

this will solve your problem;
于 2013-10-23T10:57:46.577 回答
0

Your nested if-else statement is not correct. If-else condition should be

if(R==1749){
    yourphone = "Galaxy Mega 5.8";
}
else if(R==1726){
    yourphone = "Xperia Z";
}
else{
     yourphone = "NO Result";
}
于 2013-10-23T10:57:09.987 回答