我对将 ARRAYLIST 值从一个类传递到另一个类感到困惑。我以前在这些课程中使用过 ARRAY。我用 ARRAYLISTS 改变了那些。
我有2节课。这个类有一个称为“locationcells”的ARRAYLIST。该程序从另一个类中获取 3 个随机数字并获取使用输入并检查它们的输入是否与 3 个数字匹配。这更像是一个猜谜游戏。
import java.util.ArrayList;
class SimpleDotCom {
private ArrayList<String> locationcells;
public void setLocationcells(ArrayList<String> Locs)
{
locationcells = Locs;
}
public String CheckYourself(String StringGuess)
{
String result = " Miss";
int index = locationcells.indexOf(StringGuess);
if (index >= 0)
{
locationcells.remove(index);
if (locationcells.isEmpty())
{
result = "Kill";
}
else
{
result = "Hit";
}
}
return result;
}
}
这看起来不错。现在具有 main 方法的类:
import java.util.ArrayList;
class SimpleDotComGame {
public static void main(String[] args)
{
int numOfGuesses = 0;
GameHelper helper = new GameHelper();
SimpleDotCom theDotCom = new SimpleDotCom();
/*
this is the part I don't understand. I used to have the int array and generated random numbers and it worked well.
int randomNum = (int) (Math.random() * 5);
ArrayList<String> locations = new ArrayList<String>();
*/
theDotCom.setLocationcells(locations);
boolean isAlive = true;
while (isAlive == true)
{
String guess = helper.getUserInput("Enter a number");
String result = theDotCom.CheckYourself(guess);
numOfGuesses++;
if (result.equals("Kill"))
{
isAlive = false;
System.out.println("You took " + numOfGuesses + "guesses");
}
}
}
}
如果您看到上面的评论部分。这就是我感到困惑的部分。我曾经在那里有一个数组。INT 数组。所以我能够将 INT 随机数传递给“simpledotcom”类。现在它是一个字符串类型的数组列表,我不知道如何前进。
谢谢大家,