返回原始起始位置,不退出应用程序并再次打开它

时间:2016-10-01 14:11:42

标签: java android function android-studio

应用程序的目的非常简单。要求用户输入一个号码并检查用户号码和随机创建的号码是否相同。在用户输入正确的号码之前,它会继续。一旦用户输入正确的号码,我如何更改我的随机数,以便他们可以继续而不退出应用程序。现在我必须退出一旦我找到正确的号码。然后再打开它。
    公共类MainActivity扩展AppCompatActivity {         int数; // Global Variabble。

    public void clicked (View view ){
       EditText userinput = (EditText)findViewById(R.id.userinput);
       String inputstring = userinput.getText().toString();
       if (inputstring == " "){
          Toast.makeText(getApplicationContext(),"You havent entered anything",Toast.LENGTH_SHORT).show();
    }

    int inputint = Integer.parseInt(inputstring);

    if (inputint > number ){
        Toast.makeText(getApplicationContext(),"No, too high",Toast.LENGTH_SHORT).show();
    }
    else if (inputint < number){
        Toast.makeText(getApplicationContext(),"No, too small",Toast.LENGTH_SHORT).show();
    }
    else{
        Toast.makeText(getApplicationContext(),"Well Done! You Guessed it",Toast.LENGTH_SHORT).show();

    }

        //System.out.println("Computer guessed number is: " + number);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    Random r = new Random();
    number = r.nextInt(21);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

}

2 个答案:

答案 0 :(得分:1)

你可以试试像这样的随机函数

public void randomGenerator()
{
  Random r = new random
  number = r.nextInt(21) //put the int number creation in global
}

然后在onCreate()

上调用它
    @Override
protected void onCreate(Bundle savedInstanceState) {

    randomGenerator()
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

也在else语句

else{
        Toast.makeText(getApplicationContext(),"Well Done! You Guessed it",Toast.LENGTH_SHORT).show();

        randomGenerator(); //random number after user get correct answer

    }

答案 1 :(得分:0)

你可以把

Random r = new Random(); number = r.nextInt(21); userinput.setText("");

在一个函数中,并在第一次调用你的意图时(在创建时)调用它,并在使用找到好数字时再次调用它