I want to make a random color code generator and it also works, but instead of simply giving me the color it also spits out "null" right before it.
So in the end my output looks like [nullBlue, nullgreen, nullyellow, nullred]
anybody know a quick fix?
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;
}
}
CodePudding user response:
When you create an array in Java, the elements in the array will initially have a default value. For non-primitives, this value is null
. So farbcode = new String[4]
will create a new array that can store 4 String
's, but initially it will contain 4 null
values.
You use farbcode[i] = "Some value"
with farbcode[i]
initially being null
. When you append a String to a null
value, the null
will be converted to the string "null"
, to which the string will be appended.
So for example
String str = null "String"; // Will become "nullString"
String str = null;
str = "String"; // Same as above
So, to prevent this from happening, make sure that the elements in the array don't contain the value null
when appending values to it.
You can use Arrays.fill(farbcode, "");
to set all the elements in the array to an empty string at the beginning of your loop.
As an aside, Java has a built-in function to convert an array to a string. You can replace your stringo()
function with Arrays.toString(farbcode)
.