[英]Why does every element in my array start with "null"?
我想制作一个随机颜色代码生成器,它也可以工作,但不是简单地给我颜色,它还会在它之前吐出“null”。
所以最后我的 output 看起来像[nullBlue, nullgreen, nullyellow, nullred]
有人知道快速修复吗?
public class rndmcode {
int[] secretcode = new int[4];
String[] farbcode = new String[4];
public rndmcode() { // array "secretcode" wird definiert
for (int i = 0; i < 4; i++) { //Schleife um eine Randomziffer von 1-6 zu erstellen und
Random zufallszahl = new Random();
int rndnumber = zufallszahl.nextInt(7); //Die Zahlen 1-6 sind meine Farben, die vorrerst nur Zahlen sind
switch (rndnumber) {
case 1:
farbcode[i] += "Blau";
break;
case 2:
farbcode[i] += "Rot";
break;
case 3:
farbcode[i] += "Gelb";
break;
case 4:
farbcode[i] += "Grün";
break;
case 5:
farbcode[i] += "Lila";
break;
case 6:
farbcode[i] += "Orange";
default:
if (farbcode == null)
break;
}
}
}
public String stringo() {
String s = "[";
for (String element : farbcode) {
s += element;
s += ", ";
}
s += "]";
return s;
}
}
在 Java 中创建数组时,数组中的元素最初将具有默认值。 对于非基元,此值为null
。 因此farbcode = new String[4]
将创建一个可以存储 4 个String
的新数组,但最初它将包含 4 个null
值。
您使用farbcode[i] += "Some value"
与farbcode[i]
最初是null
。 当您将 append 字符串转换为null
值时, null
将转换为字符串"null"
,该字符串将附加到该字符串。
所以例如
String str = null + "String"; // Will become "nullString"
String str = null;
str += "String"; // Same as above
因此,为防止这种情况发生,请确保数组中的元素在向其附加值时不包含值null
。
您可以使用Arrays.fill(farbcode, "");
在循环开始时将数组中的所有元素设置为空字符串。
顺便说一句,Java 有一个内置的 function 可以将数组转换为字符串。 您可以将您的stringo()
function 替换为Arrays.toString(farbcode)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.