Java 如何将字符串值存储在字符串数组中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32411696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store string values in string array?
提问by M.Reddy
I wanted to store name values in String a[] = new String[3];
我想将名称值存储在 String a[] = new String[3];
public static void main(String[] args) throws IOException {
BufferedReader bo = new BufferedReader(new InputStreamReader(System.in));
String name = bo.readLine();
String a[] = new String[3];
}
}
回答by ka4eli
If your name
represents names separated by space, try this:
如果您的name
代表名称由空格分隔,请尝试以下操作:
String a[] = name.split(" ");
回答by burglarhobbit
I guess this should suffice:
我想这应该足够了:
String a[] = new String[3];
for(int i=0; i<a.length;i++) {
String name = bo.readLine();
a[i] = name;
}
回答by D. Dimitri?
If you're working from the console I think this is the easiest way for a beginner to tackle user input:
如果您从控制台工作,我认为这是初学者处理用户输入的最简单方法:
import java.util.Scanner;
public class ReadToStringArray {
private static String[] stringArray = new String[3];
// method that reads user input into the String array
private static void readToArray() {
Scanner scanIn = new Scanner(System.in);
// read from the console 3 times
for (int i = 0; i < stringArray.length; i++) {
System.out.print("Enter a string to put at position " + i + " of the array: ");
stringArray[i] = scanIn.nextLine();
}
scanIn.close();
System.out.println();
}
public static void main(String[] args) {
readToArray();
// print out the stringArray contents
for (int i = 0; i < stringArray.length; i++) {
System.out.println("String at position " + i + " of the array: " + stringArray[i]);
}
}
}
This method uses the java's native Scanner class. You can just copy and paste this and it will work.
此方法使用 java 的本机 Scanner 类。您可以复制并粘贴它,它会起作用。