如何在字符串数组中存储字符串值?

时间:2015-09-05 09:50:45

标签: java string

我想在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];
    }
}

3 个答案:

答案 0 :(得分:5)

我想这应该足够了:

String a[] = new String[3];

for(int i=0; i<a.length;i++) {
    String name = bo.readLine();
    a[i] = name;
}

答案 1 :(得分:1)

如果您的name代表以空格分隔的名称,请尝试以下操作:

String a[] = name.split(" ");

答案 2 :(得分:0)

如果您在控制台上工作,我认为这是初学者解决用户输入的最简单方法:

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]);
        }
    }
}

此方法使用java的本机Scanner类。您只需复制并粘贴它即可。