我正在尝试创建一个工具,将当前年份与事件发生年份进行比较,然后允许用户猜测自该事件发生以来已经过了多少年。例如,首届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!");
}
}
});
}
}
...但是,测试时值继续出错。我在这里错过了什么?我的数学有问题吗?还是代码?或两者兼而有之?
答案 0 :(得分:0)
它与你的if语句的逻辑有关。当用户猜对时,&#34;输出&#34;应该等于0,这会被你的第一个条件抓住。
答案 1 :(得分:0)
简单的逻辑错误。
if (output < 1) {
result.setText("Guess again! You guessed too low!");
}
应该是......
if (output < -1) {
result.setText("Guess again! You guessed too low!");
}
忘记让低比较为负。