【发布时间】:2019-12-30 20:49:27
【问题描述】:
我是 Java 和编程的菜鸟,我正在制作一个应用程序,用户试图根据图片猜测城市。用户看到一张城市的图片,图片下方有三个按钮,其中有不同的答案。图片是从一个数组中随机生成的,并且按钮文本会发生变化,因此至少有一个按钮具有正确的答案。我想要一个带有“正确”的 TextView 来显示用户是否正确,一个带有“不正确”的 TextView 来显示用户是否错误。按下任何按钮时都会显示文本,而不是按下具有正确文本的按钮时。所以这就是我尝试过并坚持的。是的,我知道我的代码中有很多错误,例如方法名称等。我稍后会更改这些。
我有三个设置为 false 的布尔值,它们代表按下了哪个按钮。以后你会明白的。
Boolean test1 = false;
Boolean test2 = false;
Boolean test3 = false;
在 main 中,我有三个按钮,它们都调用 checkanswer 功能。他们也都在那里将自己的布尔值变为真,你很快就会知道为什么。其中一个按钮的示例。
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
test1 = true;
checkanswer();
}
});
这里是checkanswer函数
public void checkanswer() {
DisplayRandomImage();
//Giving three strings random city names from the "cities" array.
Random rndBtnTxt = new Random();
String randomCity1 = cities[rndBtnTxt.nextInt(cities.length)];
String randomCity2 = cities[rndBtnTxt.nextInt(cities.length)];
String randomCity3 = cities[rndBtnTxt.nextInt(cities.length)];
//Setting the random city names to the three different buttons.
btn1.setText(randomCity1);
btn2.setText(randomCity2);
btn3.setText(randomCity3);
//takes the picked image from the "DisplayRandomImage" method.
String str = String.valueOf(pickedImg);
//Tells what to call the different pictures, they are known as numbers make sure they are given names instead.
if (pickedImg == 0)
str = "venice";
if (pickedImg == 1)
str = "new york";
//If-statement checking so that atleast one button has the correct answer.
if (randomCity1 != str || randomCity2 != str || randomCity3 != str) {
Random rndbtn = new Random();
Button x = btnArray.get(rndbtn.nextInt(btnArray.size()));
//Sets one of the three buttons so that it has the correct answer.
x.setText(str);
}
//See where the correct answer is
String buttonText1 = btn1.getText().toString();
String buttonText2 = btn2.getText().toString();
String buttonText3 = btn3.getText().toString();
//check if the button that the user pressed has the correct answer
if (test1.equals(true) && buttonText1.equals(str)){
CorrectAnswer();
test1 = false;
}
if (test2.equals(true) && buttonText2.equals(str)){
CorrectAnswer();
test2 = false;
}
if (test3.equals(true) && buttonText3.equals(str)){
CorrectAnswer();
test3 = false;
}
else
WrongAnswer();
}
我不确定我在这里做错了什么。例如,当我按下“btn1”时,“test1”设置为 True,如果“buttontext1”等于“str”,它应该可以工作。但由于某种原因,这三个按钮中的哪一个调用 CorrectAnswer 方法似乎是随机的。我在这里做错了什么?
【问题讨论】: