gpt4 book ai didi

java - 为什么我的应用程序在我单击某个按钮时崩溃?

转载 作者:行者123 更新时间:2023-11-30 10:50:43 25 4
gpt4 key购买 nike

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

最佳答案

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

关于java - 为什么我的应用程序在我单击某个按钮时崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34972184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com