大家好,所以我很新的Java和這個代碼下面肯定會證明這一點。 我非常感謝任何提示我出錯的地方,謝謝!爲什麼當我點擊某個按鈕時,我的應用程序崩潰?
我試圖創建一個簡單的應用程序,顯示一個隨機的報價,並給出了猜測誰說的機會。
可以肯定的主要問題有---> if(guessNameInt == whoSaidItInt) 因爲它只會在我點擊啓用tryLuck if語句的按鈕時崩潰。
我的繼承人下面
int randomNum;
String whoSaidIt;
// quotes and numbers
public void randomRick(View view) {
if (randomNum == 0) {
Toast.makeText(getApplicationContext(), "Life is effort and I'll stop when I die!", Toast.LENGTH_LONG).show();
whoSaidIt = "Jerry";
}
if (randomNum == 1) {
Toast.makeText(getApplicationContext(), "Well look where being smart got you.", Toast.LENGTH_LONG).show();
whoSaidIt = "Jerry";
}
if (randomNum == 2) {
Toast.makeText(getApplicationContext(), "Ohh yea, you gotta get schwifty.", Toast.LENGTH_LONG).show();
whoSaidIt = "Rick";
}
}
public void tryLuck(View view) {
EditText guessedName = (EditText) findViewById(R.id.authorIs);
String guessedNameString = guessedName.getText().toString();
int guessNameInt = Integer.parseInt(guessedNameString);
int whoSaidItInt = Integer.parseInt(whoSaidIt);
if (guessNameInt == whoSaidItInt) {
Toast.makeText(getApplicationContext(), "Holy crow, Good job!", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Try again", Toast.LENGTH_LONG).show();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random randomGenerator = new Random();
randomNum = randomGenerator.nextInt(3);
}`
沒有堆棧跟蹤,這是很難說,但它是非常奇怪的,你想爲一個字符串(guessedNameString)轉換爲int(數字)。因此,如果您輸入「Albert Einstein」,並將其轉換爲int,則Java代碼將引發錯誤。解決方案?不要將它轉換爲int :-)解決方案可能涉及比較字符串,所以如果你這樣做,請使用.equals,而不是==。只是谷歌。 –
您將該名稱設置爲一個字符串'whoSaidIt =「瑞克」;'但你嘗試分析它的整數'的Integer.parseInt(whoSaidIt);'。這是行不通的 – Arc676
郵報([編輯])您的logcat –