[英]I can't stop null from showing up in my output for my 1d array in java
I am struggling to declare i as an interger and I can't figure out why the output is coming out as null.我很难将 i 声明为整数,但我无法弄清楚为什么 output 会以 null 的形式出现。 The goal is to make a sequence My code is:
目标是制作一个序列我的代码是:
public static void main(String[] args) {
String[] myArray = new String[10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j <= i; j++) {
myArray[i] = myArray[i] + "A";
}
System.out.println(myArray[i]);
}
}
The problem is that none of the items inside the array has value, therefore they are null
.问题是数组中的所有项目都没有价值,因此它们是
null
。 You can use the following code which initialize all item whith an empty string in the first loop:您可以使用以下代码在第一个循环中使用空字符串初始化所有项目:
for (int i = 0; i < 10; i++) {
myArray[i] = "";
for (int j = 0; j <= i; j++) {
myArray[i] = myArray[i] + "A";
}
System.out.println(myArray[i]);
}
public static void main(String[] args) {
String[] myArray = new String[10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j <= i; j++) {
myArray[i] = myArray[i] + "A";
}
System.out.println(myArray[i]);
}
}
At this line在这一行
myArray[i] = myArray[i] + "A";
myArray[i] = myArray[i] + "A";
myArray[i] at the right side is null, so concatinating "A" with a null will make it null again.右侧的 myArray[i] 是 null,因此将“A”与 null 连接将使其再次变为 null。 You should initialize each myArray[i] as Answered by Amir MB or can try this:
您应该按照 Amir MB 的回答初始化每个 myArray[i],或者可以试试这个:
public static void main(String[] args) {
String[] myArray = new String[10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j <= i; j++) {
myArray[i] = "A" + myArray[i];
}
System.out.println(myArray[i]);
}
}
for (int i = 0; i < 10; i++) {
myArray[i] = "";
for (int j = 0; j <= i; j++) {
myArray[i] = myArray[i] + "A";
}
System.out.println(myArray[i]);
}
String[] myArray = new String[10];
This is an object array and all objects are initialized to null, if there is no explicit value assigned to it.这是一个 object 数组,如果没有为其分配显式值,则所有对象都初始化为 null。
So, each element of the array needs to be assigned to a empty string;因此,需要将数组的每个元素分配给一个空字符串; do it in the first for loop as mentioned above.
如上所述,在第一个 for 循环中执行此操作。
Or, assign values during array declaration itself.或者,在数组声明本身期间赋值。 Worth for a small sized array, but won't recommend for a larger one.
适合小型阵列,但不推荐大型阵列。
String[] myArray = new String[]{"", "", "", "", "", "", "", "", "", ""};
Arrays class has a fill method. Arrays class 有填充方法。
String[] myArray = new String[10];
Arrays.fill(myArray, "");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.