-3

嗨,我试图计算 if/else 但它不起作用。每次您尝试找到数字 32 时,它都应该计数 +1。这对我不起作用..所以...我希望它计算我为找到第 32 号所做的所有尝试,因此它显示我尝试了多少次。

谁能帮我吗?

String antwoord = null;
int getal = 32;
int count = 0;


if((Integer.parseInt(txt_input.getText().toString()) ) == getal)
{
    antwoord = "Goed! in: " + count + " keer";
}
else if((Integer.parseInt(txt_input.getText().toString()) ) <= getal)
{
    antwoord = "Hoger... ";
    count++;
} 
else if((Integer.parseInt(txt_input.getText().toString()) ) >= getal)
{
    antwoord = "Lager... ";
    count++;
}
count++;

lbl_hoger_lager.setText(antwoord);
4

5 回答 5

2

你正在混合你的逻辑if(condition).

它应该是

if(number is equal){
    // some operation
}
else if(number is greater){
   // some operation
}
else if(number is lesser than X ){
   // some operation
}

希望这可以帮助。

于 2013-09-10T12:28:09.740 回答
1

我想你想这样做:

        String antwoord = null;
        int getal = 32;
        int count = 0;

        if ((Integer.parseInt(txt_input.getText().toString())) == getal) {
            count++;
            antwoord = "Goed! in: " + count + " keer";

        } else if ((Integer.parseInt(txt_input.getText().toString())) < getal) {
            antwoord = "Hoger... ";
            // count++;
        }

        else if ((Integer.parseInt(txt_input.getText().toString())) > getal) {
            antwoord = "Lager... ";
            // count++;
        }

        lbl_hoger_lager.setText(antwoord);
于 2013-09-10T12:28:03.507 回答
1

一些提示:

  1. 您应该避免使用长字符串的通用代码。例如(Integer.parseInt(txt_input.getText().toString()) )出现 3 次。这是一个漫长而复杂的表达。只评估一次并将结果存储在局部变量中怎么样?

    int userInput = (Integer.parseInt(txt_input.getText().toString()) );
    

    (而且.toString()可能也没有必要)

  2. 如果您想始终计数,请在if.

  3. count是一个局部变量。0每次执行代码时都会如此。如果要保留以前尝试的值,则必须使用字段。

于 2013-09-10T12:33:36.673 回答
0

我刚刚用你的代码进行了测试,对我来说它看起来不错,显然有一些变化:

public class A

{ public static void main(String [] args) { String antwoord = null; int getal = 32; 整数计数 = 0;字符串 k =“32”;

    if((Integer.parseInt(k) ) == getal)
        {
            antwoord = "Goed! in: " + (count+1) + " keer";
        }
    else if((Integer.parseInt(k) ) <= getal)
        {
            antwoord = "Hoger... ";
            count++;
        }

    else if((Integer.parseInt(k) ) >= getal)
    {
            antwoord = "Lager... ";
            count++;
        }
       // count++;

        System.out.println(antwoord);
    //lbl_hoger_lager.setText(antwoord);
}

}

输出是:

Goed! in: 1 keer
于 2013-09-10T12:29:29.367 回答
0

按照您的设置方式,如果输入大于或小于 32,计数将递增。

这应该适合你:

String antwoord = null;
int getal = 32;
int count = 0;


if((Integer.parseInt(txt_input.getText().toString()) ) == getal)
{
    antwoord = "Goed! in: " + count + " keer";        
}
else if((Integer.parseInt(txt_input.getText().toString()) ) < getal)
{
    antwoord = "Hoger... ";    
    count++;
} 
else if((Integer.parseInt(txt_input.getText().toString()) ) > getal)
{
    antwoord = "Lager... ";    
    count++;
}

lbl_hoger_lager.setText(antwoord);
于 2013-09-10T12:29:32.317 回答