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