英文:
What am i doing wrong. copy the the values of s1 into the element von s2
问题
我试图将变量s1的值复制到s2的元素中,但是我得到了null。我做错了什么?以下是我的代码:
public class Main {
public static void main(String[] args) {
String[] s1 = new String[10];
String[] s2 = new String[10];
String[] s3 = new String[10];
for (int i = 0; i < s1.length; i++){
s2[i] = s1[i];
System.out.println("s2[" + i + "] : " + s2[i]);
}
}
}
-------- 输出 -------
s2[0] : null
s2[1] : null
s2[2] : null
s2[3] : null
s2[4] : null
s2[5] : null
s2[6] : null
s2[7] : null
s2[8] : null
s2[9] : null
英文:
I am trying to copy the values of the variable s1 into the element of s2 and I am getting null. What am I doing wrong. Here are my Code:
public class Main {
public static void main(String[] args) {
String[] s1 = new String[10];
String[] s2 = new String[10];
String[] s3 = new String[10];
for (int i = 0; i < s1.length; i++){
s2[i] = s1[i];
System.out.println("s2[" + i + "] : " + s2[i]);
}
}
}
-------- output -------
s2[0] : null
s2[1] : null
s2[2] : null
s2[3] : null
s2[4] : null
s2[5] : null
s2[6] : null
s2[7] : null
s2[8] : null
s2[9] : null
答案1
得分: 2
你已经创建了一个空的字符串数组,但是尚未为各个字符串分配任何内容。字符串默认为 null
,因此您的输出是完全正常的。
您还可以阅读这篇有趣的帖子:https://stackoverflow.com/questions/5389200/what-is-a-java-strings-default-initial-value
如果您希望看到与 null 不同的任何结果,您必须通过以下方式初始化第一个数组:
String[] s1 = {"第一个字符串", "第二个字符串", ...}
或者(在 for 循环之前,显然):
s1[1] = "第一个字符串";
s1[2] = "第二个字符串";
...
英文:
You have created an empty array of Strings, but you have not assigned any content to the individual strings. A string defaults to null
, so your output is completely normal.
You can also read this interesting post: https://stackoverflow.com/questions/5389200/what-is-a-java-strings-default-initial-value
If you want to see any result different from null, you have to initialize the first array, by using:
String[] s1 = {"First string", "Second string", ... }
or (before the for loop, obviously)
s1[1] = "First string"
s1[2] = "Second string"
...
答案2
得分: 1
以下是您要求的翻译内容:
你错过了初始化s1数组的步骤。默认情况下,它将包含空值,而您正在将这些空值复制到s2中,因此得到了空值。
public class Main {
public static void main(String[] args) {
String[] s1 = {"A", "B", "C", "D"};
String[] s2 = new String[10];
String[] s3 = new String[10];
for (int i = 0; i < s1.length; i++){
s2[i] = s1[i];
System.out.println("s2[" + i + "] : " + s2[i]);
}
}
}
英文:
You missed out to initialise s1 array. By default, it will contains null values which you are copying into s2, hence null values.
public class Main {
public static void main(String[] args) {
String[] s1 = {"A", "B", "C", "D"};
String[] s2 = new String[10];
String[] s3 = new String[10];
for (int i = 0; i < s1.length; i++){
s2[i] = s1[i];
System.out.println("s2[" + i + "] : " + s2[i]);
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论