我对编程非常陌生,我在android studio中制作了一个非常简单的猜谜游戏应用程序,但是我想知道如果用户输入的整数小于1且大于100,如何添加错误消息?这是我目前的代码:
public class MainActivity extends AppCompatActivity {
private EditText txtGuess;
private Button btnGuess;
private TextView lblOutput;
private int theNumber;
private int numberOfTries;
public void checkGuess() {
String guessText = txtGuess.getText().toString();
String message = "";
try {
lblOutput.setVisibility(View.VISIBLE);
numberOfTries = numberOfTries + 1;
int guess = Integer.parseInt(guessText);
if (guess < theNumber)
message = guess + " is too low. Try again.";
else if (guess > theNumber)
message = guess + " is too high. Try again.";
else {
message = guess +
" is correct! This took you " + numberOfTries + " tries! Let's play again.";
lblOutput.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this, message,
Toast.LENGTH_LONG).show();
newGame();
numberOfTries = 0;
}
} catch (Exception e) {
message = "Enter a whole number between 1 and 100.";
}
finally {
lblOutput.setText(message);
txtGuess.requestFocus();
txtGuess.selectAll();
}
}
public void newGame() {
theNumber = (int) (Math.random() * 100 + 1);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtGuess = (EditText) findViewById(R.id.txtGuess);
btnGuess = (Button) findViewById(R.id.btnGuess);
lblOutput = (TextView) findViewById(R.id.lblOutput);
newGame();
btnGuess.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkGuess();
}
});
txtGuess.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
checkGuess();
return true;
当前它只是告诉用户该数字太大。非常感谢您的帮助,谢谢!
答案 0 :(得分:0)
如果满足特定条件,则可以引发自定义异常:
https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html https://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
喜欢:
if( number > 100 && number < 1){
throw new CustomException("Number not in defined range");
}
public class CustomExceptionextends Exception {
public CustomException(String message){
super(message);
}
}
答案 1 :(得分:0)
例如,您可以创建一个验证方法:
布尔布尔值验证(整数){ }
如果给定数字有效,则返回true;如果超出范围或格式错误等,则返回false。
然后在您的checkGuess方法中,在用户输入上并且返回的值等于false的情况下,请调用validate()显示Toast。
自定义异常也是一种解决方法。
答案 2 :(得分:0)
我想知道为什么要在这里使用异常。您只需在真实时间内检查用户输入,如果输入有效,就可以中断循环。
while(true){ //check input is valid
if(inputNumber < 1 || inputNumber > 100){
sout("plz enter number between 1 to 100");
}
else{
break();
}
}
//now that you are sure input is valid go on.
这里的要点是,用户每次输入无效数字都不会获得异常,并且可以尝试重复输入数字而不会被应用程序异常打扰,而输入有效数字则可以继续。