我计划打印一条消息,以显示数组中的数据结果。它假设看起来像
"7 *******"
但我得到了"7 null*******"
。
我想摆脱“null”
import java.util.ArrayList;
public class FavorGameDisplay
{
private ArrayList<String> votedGame;
private String[] asterisk;
private int[] gameCount;
/**
* Constructor for objects of class FavorGameDisplay
*/
public FavorGameDisplay()
{
FavorGameData data = new FavorGameData();
votedGame = data.getData();
analyzeData();
}
/**
* Analyze and recording counts of the following video games:
* gameCount[0]: Nier: Automata
* gameCount[1]: PlayerUnknown’s Battlegrounds
* gameCount[2]: Wolfenstein 2: The New Colossus
* gameCount[3]: Cuphead
* gameCount[4]: any other video games
*/
private void analyzeData()
{
gameCount = new int[5];
asterisk = new String[5];
for (String game : votedGame)
{
if (game.equals("Nier: Automata"))
{
gameCount[0]++;
asterisk[0] += "*";
}
else if (game.equals("PlayerUnknown’s Battlegrounds"))
{
gameCount[1]++;
asterisk[1] += "*";
}
else if (game.equals("Wolfenstein 2: The New Colossus"))
{
gameCount[2]++;
asterisk[2] += "*";
}
else if (game.equals("Cuphead"))
{
gameCount[3]++;
asterisk[3] += "*";
}
else
{
gameCount[4]++;
asterisk[4] += "*";
}
}
}
/**
* Display the analyzed data as a histogram
*/
public void displayData()
{
System.out.println("------------------------------------------");
System.out.println("Number of people vote for each game: ");
System.out.println("Nier: Automata: " + gameCount[0] + " " + asterisk[0]);
System.out.println("PlayerUnknown’s Battlegrounds: " + gameCount[1] + " " + asterisk[1]);
System.out.println("Wolfenstein 2: The New Colossus: " + gameCount[2] + " " + asterisk[2]);
System.out.println("Cuphead: " + gameCount[3] + " " + asterisk[3]);
System.out.println("Others: " + gameCount[4] + " " + asterisk[4]);
System.out.println("------------------------------------------");
}
}
答案 0 :(得分:2)
您不首先初始化asterisk
的元素;所以当你写:
asterisk[0] += "*";
您将其当前值(null
)的字符串表示与"*"
连接起来,因此最终得到null*
。
在循环之前用空字符串填充数组:
Arrays.fill(asterisk, "");