如何在用户猜对了之后更改随机数,并在用户输入错误的数据类型时显示消息

时间:2015-12-16 04:48:48

标签: java android exception

我正在制作一个随机数猜测应用,但该应用仅运行一次,您必须重新启动应用再次播放,如何让用户在通过更改猜到正确的结果后再次播放随机数再次。 此外,我希望该应用程序检测用户是否在文本字段中输入了错误的数字或字符串,我该怎么做? 任何帮助将不胜感激,谢谢!

    int randomNumber;

public void output(View view)
{
    EditText guess = (EditText) findViewById(R.id.editText);
    String guessedNumberString = guess.getText().toString();

    int guessedNumberInt = Integer.parseInt(guessedNumberString);

    String message = "";
    try {
        if (guessedNumberInt > randomNumber) {
            message = "Too high";
        } else if (guessedNumberInt < randomNumber) {
            message = "Too low";
        } else {
            message = "You are right! Try it again!";
        }
    }
    catch (InputMismatchException e)
    {
        message = "Enter a valid number";
    }
    Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
}

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Random randomGenerator = new Random();
    randomNumber = randomGenerator.nextInt(21);
}

3 个答案:

答案 0 :(得分:0)

我知道有两种方式: 1.创建一个startGame方法来设置游戏,即生成随机,并在你的输出方法中,在用户猜对之后调用它 2.用它来刷新整个活动完成(); startActivity(getIntent());

第二部分在转换为整数

之前玩一些if else

答案 1 :(得分:0)

这是逻辑:

 if(input == randNum){


ReLaunchGame();

}

现在,对于方法ReLaunchGame(),您必须重新启动活动,或重置所有文本字段。

只需将他们的输入与您选择的随机数进行比较。现在,看看他们是否输入了错误的输入。您必须首先了解异常处理,我认为您这样做。

enter image description here

http://www.mathcs.emory.edu/

Scanner sc=new Scanner(System.in);
try
{
  System.out.println("Please input an integer");
  //nextInt will throw InputMismatchException
  //if the next token does not match the Integer
  //regular expression, or is out of range
  int usrInput=sc.nextInt();
}
catch(InputMismatchException exception)
{
  //Print "This is not an integer"
  //when user put other than integer
  System.out.println("This is not an integer");
}

多数民众赞成。让我知道它是否有效! : - )

答案 2 :(得分:0)

要检查用户是否输入了号码,请将parseInt()行放在try块内。 您必须在此处捕获的例外是NumberFormatException。 所以看起来应该是这样的:

try {
    int guessedNumberInt = Integer.parseInt(guessedNumberString);
    ...
}
catch (NumberFormatException e) {
    message = "Enter a valid number";
}

我不熟悉Android,因此我不知道何时调用output()函数。但是,您可以尝试在try块之前创建一个标志,以指示用户是否正确猜到了该号码。然后,如果标志为true,则在函数末尾创建另一个随机数。您还需要将randomGenerator作为类变量。

Random randomGenerator = new Random();
public void output(View view)
{
    ...
    boolean correct = false;
    try {
        ...
        } else {
            message = "You are right! Try it again!";
            correct = true;
        }
    }
    ...
    Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
    if (correct) {
        randomNumber = randomGenerator.nextInt(21);
    }
}