2016-10-01 39 views
0

應用程序的目的非常簡單。要求用戶輸入一個號碼並檢查用戶號碼和隨機創建的號碼是否相同。直到用戶輸入正確的號碼,它纔會繼續。一旦用戶輸入正確的號碼,我如何更改我的隨機號碼,以便他們可以繼續而不必退出應用程序。現在我必須退出,一旦找到正確的號碼,並再次打開它。
public class MainActivity extends AppCompatActivity {intl number; //全局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); 
} 

}

+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

是的,我不這麼想。它必須首先在全球範圍內創建 –

0

你可以把

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

的功能,並調用它時,你的目的是呼籲第一次(在上創建),然後重新校準它當使用發現好號碼