簡體   English   中英

If-else語句不適用於模型

[英]If-else statements not working for model

我想要的是

在JPanel上,我有一個JButton和一個JTextArea。 按下JButton時,必須在JTextArea內部打印某些文本。 該特定文本由if-else語句確定。 if-else的條件基於整數變量R。

基本上,它是一項調查,例如我要進行的問答。 我使用R記錄用戶的答案。 當用戶單擊一個選項時,R的值將更新。

我使用String變量yourphone。 如果最后的R值為例如120,則您的電話將更新為字符串,例如。 XperiaZ。

我正在討論的最后一個JPanel是顯示結果的地方。 R的總值用於if-else語句中。

結構體

我這樣初始化變量

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);

結果輸出為“否結果1749”。 這是不可能的,因為它表明R的值已更新。 如果其值為1749,則輸出應為“ Galaxy Mega 5.8”。 我不知道當明顯滿足if條件時,為什么它會從else語句中獲取yourphone的輸出。

如果滿足以下條件,則需要先添加else

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

否則,即使R == 1749 ,您的yourphone也將是"NO Result"

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

this will solve your problem;

您的嵌套if-else語句不正確。 If-else條件應為

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

暫無
暫無

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

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