Java - How to scan a String into an Array?

23,537

If you're receiving input from the console and can safely assume that it is not going to be formatted improperly you can use:

Scanner in = new Scanner(System.in):  //receives input from the console
String line = in.nextLine(); //receives everything they type until they hit enter

That would take in all the information they enter. If their input is:

"Jaime Smiths, abcd5432, Sydney, how's going"

You can then split the values by comma:

String[] values = line.split(",");
for(String s: values)
    System.out.println(s);

Gives the following output:

"Jaime Smiths"
" abcd5432"
" Sydney"
" how's going"

You'll want to remove trailing and or leading space characters, but that will give you the values you want, and you can then concatenate them and add them to the existing array:

friends[5] = new Friend(values[0], values[1], values[2], values[3]);
Share:
23,537
user2714582
Author by

user2714582

Updated on July 09, 2022

Comments

  • user2714582
    user2714582 almost 2 years

    I'm having trouble with putting scanned information into array in Java.

    private void initializeFriends()
    {
        //initialize the size of array:
        friends = new Friend[200];
        //initialize the first 5 objects(Friends):
        friends[0] = new Friend("Rodney Jessep", "rj2013", "Brisbane", "hi!");
        friends[1] = new Friend("Jaime Smiths", "abcd5432", "Sydney", "how's going");
        friends[2] = new Friend("William Arnold", "william1994", "Brisbane", "boom");
        friends[3] = new Friend("James Keating", "qwerty52", "Newcastle", "Hey");
        friends[4] = new Friend("Amy Richington", "IAmRichAmy", "Perth", "Yo");
    }
    

    After the procedure above is run, a method called addFriends() is run where a scanner comes in to put data into friend structure.

    What is the best way to scan in information into an array? Would using the Scanner in = new Scanner(System.in); feature be wise since there are so many different elements in 'Friend': (String name, String username, String city, String message)?