Java:如何初始化字符串[]?

Java:如何初始化字符串[]?,java,string,initialization,Java,String,Initialization,错误 % javac StringTest.java StringTest.java:4: variable errorSoon might not have been initialized errorSoon[0] = "Error, why?"; 代码 public class StringTest { public static void main(String[] args) { String[] errorSoon

错误

% javac  StringTest.java 
StringTest.java:4: variable errorSoon might not have been initialized
        errorSoon[0] = "Error, why?";
代码

public class StringTest {
        public static void main(String[] args) {
                String[] errorSoon;
                errorSoon[0] = "Error, why?";
        }
}
您需要
errorSoon
,如错误消息所示,您只有它

这相当于

String[] errorSoon = new String[2];
errorSoon[0] = "Hello";
errorSoon[1] = "World";
n表示它需要容纳多少个字符串

您可以在声明中这样做,也可以在以后不使用字符串[]的情况下这样做,只要是在您尝试使用它们之前

String[] errorSoon = { "foo", "bar" };
--或--


你可以这样写

String[] errorSoon = {"Hello","World"};

For (int x=0;x<errorSoon.length;x++) // in this way u create a for     loop that would like display the elements which are inside the array     errorSoon.oh errorSoon.length is the same as errorSoon<2 

{
   System.out.println(" "+errorSoon[x]); // this will output those two     words, at the top hello and world at the bottom of hello.  
}
String[]errorSoon={“你好”,“世界”};

对于(int x=0;x),我相信您只是从C++迁移,在java中,必须初始化数据类型(其他原始类型,字符串不是java中的原始类型),如果它们不符合C++规范,那么就使用它们作为一个空的引用变量(很像C++上下文中的指针)。
字符串声明:

String str;
字符串初始化

String[] str=new String[3];//if we give string[2] will get Exception insted
str[0]="Tej";
str[1]="Good";
str[2]="Girl";

String str="SSN"; 
我们可以获取字符串中的单个字符:

char chr=str.charAt(0);`//output will be S`
如果我想获得如下单个字符的Ascii值:

System.out.println((int)chr); //output:83
现在我想将Ascii值转换为Charecter/Symbol

int n=(int)chr;
System.out.println((char)n);//output:S
它是初始化和获取字符串长度代码的非常简单的方式为初学者


Java8中,我们还可以使用流,例如

String[] strings = Stream.of("First", "Second", "Third").toArray(String[]::new);
如果我们已经有一个字符串列表(
stringList
),那么我们可以收集到字符串数组中,如下所示:

String[] strings = stringList.stream().toArray(String[]::new);

您可以使用下面的代码初始化大小,并将空值设置为字符串数组

String[] row = new String[size];
Arrays.fill(row, "");
如果将字符串数组传递给方法,请执行以下操作:

myFunc(arr);
或者:

myFunc(new String[] {"foo", "bar"});

也许不是OPs问题标题所建议的,但我正试图将我的字符串传递给接受字符串[]的参数,这是解决方案。您不能使用新字符串吗{“new”,“array”};
您必须
args=new String[]{“new”,“array”};
这是一个小问题,您不能使用()来用默认值实例化数组中的每个字符串。一个包含5个空字符串的数组应该是=new array[5](“”);而不是={”、“new”、“array”、“”、“”、“}。使用for循环。Java 8:
int n=(int)chr;
System.out.println((char)n);//output:S
String[] string=new String[60];
System.out.println(string.length);
String[] strings = Stream.of("First", "Second", "Third").toArray(String[]::new);
String[] strings = stringList.stream().toArray(String[]::new);
String[] row = new String[size];
Arrays.fill(row, "");
String[] arr = {"foo", "bar"};
myFunc(arr);
myFunc(new String[] {"foo", "bar"});