当我点击某个按钮时,为什么我的应用程序崩溃?

时间:2016-01-24 04:21:29

标签: java android string crash int

大家好,所以我对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);
}`

1 个答案:

答案 0 :(得分:1)

您正在尝试将String转换为Int。这只有在String是实际的int(即数字)而不是名称(Jerry或Rick)时才有效。请改用guessNameString.equals(whoSaidIt)