0

I wanted to store name values in 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];
    }
}
1
  • a[index] = name; you can do it with for(int i = 0; i < a.length; i++){a[i] = name} or you can use some variable like counter = 0; and a[counter] = name; counter++; Commented Sep 5, 2015 at 9:52

3 Answers 3

5

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

If your name represents names separated by space, try this:

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.