【问题标题】:Error in logic for year comparison tool年份比较工具的逻辑错误
【发布时间】:2015-04-30 01:27:27
【问题描述】:

我正在尝试创建一个工具,将当前年份与事件发生的年份进行比较,然后让用户猜测自该事件发生以来已经过去了多少年。例如,首届FRC锦标赛是在1992年举行的,今年是2015年,用户猜测是23年前举行的,这是正确的。

所以,在我看来,代码应该是这样的......

  public class Credits extends Activity {
    int inaugural = 1992;
    int guess;
    int differenceInYears;
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);
    int output;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_credits);
        final EditText yearGuess=(EditText)findViewById(R.id.txtYearGuess);
        Button go = (Button)findViewById(R.id.btnCalculate);
        final TextView result = ((TextView)findViewById(R.id.txtResult));
        go.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                int userGuess= Integer.parseInt(yearGuess.getText().toString());
                differenceInYears = year - inaugural;
                output = userGuess - differenceInYears;

                if (output < 1) {
                    result.setText("Guess again! You guessed too low!");
                }

                else if (output == 1) {
                    result.setText("You're REALLY close!");

                }

                else if (output == -1) {
                    result.setText("You're REALLY close!");

                }

                else if (output > 1) {
                    result.setText("Guess again! You guessed too high!");

                }

                else {
                    result.setText("Good job! You're an FRC Genious!");

                }
            }

        });
     }
    }

...但是,在测试时,这些值仍然会出错。我在这里想念什么?我的数学有问题吗?或代码?还是两者都有?

【问题讨论】:

    标签: android date if-statement logic


    【解决方案1】:

    这与你的 if 语句的逻辑有关。当用户猜测正确时,“输出”应该等于 0,这将被您的第一个条件捕获。

    【讨论】:

    • 是的。我刚刚通过使用调试变量探测工具也意识到了这一点。在我不小心点击它之前,我什至不知道存在这样的工具。谢谢!
    【解决方案2】:

    简单的逻辑错误。

    if (output < 1) {
                        result.setText("Guess again! You guessed too low!");
                    }
    

    应该是……

    if (output < -1) {
                        result.setText("Guess again! You guessed too low!");
                    }
    

    只是忘记将低比较设为负数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多