我正在为我的学校项目制作一个猜谜游戏,但我对 Android Studio 和 Java 还很陌生。
目前我的代码如下所示:
public class MainActivity extends AppCompatActivity {
public int score = 0;
int random = random();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button correct = (Button) findViewById(R.id.correct);
Button other = (Button) findViewById(R.id.other);
Button newGame = (Button) findViewById(R.id.newGame);
TextView words = (TextView) findViewById(R.id.words);
}
public Integer random (){
int random = (int )(Math.random() * 5);
return random;
}
private String list[] =
{"Dog", "Cat", "Mouse", "Elephant", "Rat", "Parrot"};
public void clickedButton(View view) {
TextView words = (TextView) findViewById(R.id.words);
if (view.getId()== R.id.newGame)
{
words.setText(list[random]);
score = 0;
Log.i("score", "score = " + score);
}
if (view.getId() == R.id.correct)
{
// set maybe new array so new textview does not give the same value
words.setText(list[random]);
score = score +1;
Log.i("score", "score = " + score);
}
if (view.getId() == R.id.other)
{
// set maybe new array so new textview does not give the same value
words.setText(list[random]);
Log.i("score", "score = " + score);
}
}
}
想法很简单。我的数组中(目前)有 6 个单词。因此,当我启动游戏时,它会在屏幕上随机显示一个单词,我必须向其他人描述该单词。如果他们猜对了,我按正确,我得到另一个词,如果没有,我可以通过并得到另一个词……好吧,我看到的问题是我有可能再次得到同一个词。所以我认为应该有办法解决这个问题。
我考虑过添加类似 if 的语句,例如 if index 1 or 2 or 3 then give another word 但如果我有 100 个单词,那将是猴子般的工作。
所以我认为我应该有机会从 like temp 中删除单词。数组,但没有内置方法可以做到这一点。
我读到有那些 arrayLists 和列表,但使用 Array 不是更容易吗?也许一些技巧如何?
原文由 osiic21 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以先创建一个
ArrayList
(因为它更灵活):然后在构造函数中初始化对象并
ArrayList
如下所示:然后您可以跟踪您阅读的最后一项的索引:
每次你阅读一个项目时,只需增加
index
:这会成功的