年份比较工具的逻辑错误

Error in logic for year comparison tool

我正在尝试创建一个工具,将当前年份与事件发生的年份进行比较,然后让用户猜测自该事件发生以来已经过去了多少年。例如,首届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!");

                }
            }

        });
     }
    }

...然而,测试时这些值继续出现错误。我在这里错过了什么?我的数学有问题吗?或代码?还是两者都有?

这与您的 if 语句的逻辑有关。当用户猜对时,"output" 应该等于 0,这会被您的第一个条件捕获。

简单的逻辑错误。

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

应该是……

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

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