我对 Java 很陌生,有一个问题。这是家庭作业,所以我不喜欢任何直接的答案。谢谢!
我正在研究玩扑克的遗传算法。我想创建一个字符串数组的 arrayList。字符串数组将保存一轮中每手可能的牌局。为了确保它正常工作,我现在想做的是运行我的方法并打印出结果。这是我的练习课(这只是作业的一小部分):::
import java.util.ArrayList;
import java.util.Arrays;
public class Play
{
GeneticAlg start;
ArrayList<Object> pop;
public static void main(String[] args)
{
GeneticAlg start = new GeneticAlg();
ArrayList<String[]> pop = start.initializePopulation();
for(String[] arr: pop)
{
System.out.println(Arrays.toString(arr));
}
}
}
import java.util.ArrayList;
import java.util.Random;
public class GeneticAlg
{
ArrayList<String[]> population;
int[] populationScores;
String[] chromosome;
int generation;
int index;
public GeneticAlg()
{
}
public ArrayList<String[]> initializePopulation()
{
ArrayList<String[]> population = new ArrayList<String[]>();
for (int i = 0; i < 20; i++)
{
Random generator = new Random();
String[] choices = {"bet","raise","call","check"};
chromosome = new String[33];
for (int j = 0; j < 33; j++)
{
if (j < 6) //first and second round possible hands)
{
index = generator.nextInt((choices.length)-1);
chromosome[j] += choices[index];
}
else //third, fourth, and fifth round possible hands)
{
index = generator.nextInt(choices.length);
chromosome[j] += choices[index];
}
}
population.add(chromosome);
}
return population;
}
}
现在,它正在打印数组,但每个条目如下所示:
[nullcall, nullraise, nullbet, nullraise, nullcall, nullraise,....
我希望它只返回前面没有空的移动。任何建议表示赞赏。谢谢!
预计到达时间:我修复了两行连接错误,但它仍然在每个命令前面打印“null”。有什么建议吗?
修复错误后的代码:
import java.util.ArrayList;
import java.util.Arrays;
public class Play
{
GeneticAlg start;
ArrayList<Object> pop;
public static void main(String[] args)
{
GeneticAlg start = new GeneticAlg();
ArrayList<String[]> pop = start.initializePopulation();
for(String[] arr: pop)
{
System.out.println(Arrays.toString(arr));
}
}
}
import java.util.ArrayList;
import java.util.Random;
public class GeneticAlg
{
ArrayList<Object> population;
String[] choices;
int[] populationScores;
String[] chromosome;
int generation;
int index;
public GeneticAlg()
{
}
public ArrayList<Object> initializePopulation()
{
population = new ArrayList<Object>();
for (int i = 0; i < 20; i++)
{
Random generator = new Random();
for (int j = 0; j < 24; j++)
{
if (j < 6) //first and second round possible hands)
{
choices[0]= "bet";
choices[1]= "raise";
choices[3]= "call";
index = generator.nextInt(choices.length);
chromosome[j] = choices[index];
}
else //third, fourth, and fifth round possible hands)
{
choices[4] = "check";
index = generator.nextInt(choices.length);
chromosome[j] = choices[index];
}
}
population.add(chromosome);
}
return population;
}
}
最佳答案
对象数组(例如Stirng
)在开始时用null
值填充,所以这样做
chromosome[j] += choices[index];
与
相同chromosome[j] = chromosome[j] + choices[index];
与
相同chromosome[j] = null + choices[index];
因此,您将 null
与 choices[index];
连接起来,例如为您提供 nullbet
。
要解决这个问题,只需使用 =
而不是 +=
。
关于Java - 打印字符串数组的数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22596519/