-3

I am trying to read a string in from a text file, split the string whenever there are spaces, and store each word in an array of strings:

eg. input "Hello i am a sentence"

output [Hello, i, am, a, sentence]

I currently have the following

Scanner sc = null;
      try
      {
        sc = new Scanner(new FileReader(args[0]));
        LinkedList<String> list = new LinkedList<String>();
        String str = sc.nextLine();
        for(String i:str.split(" ")){
           list.add(i);
        }
        String[] arguments = list.toArray(new String[list.size()]);
        System.out.println(arguments);
      }
      catch (FileNotFoundException e) {}
      finally
      {
          if (sc != null) sc.close();
      }

But i am unable to convert the list into an array and i get the following output

[Ljava.lang.String;@45ee12a7
rohaldb
  • 589
  • 7
  • 24

2 Answers2

2

You don't need to make it List and again convert into normal Array, Just simply do like this, Let's say it's your String

 String string = "Hello i am a sentence";

You can do either

 String[] array = string.split("\\s", -1);

OR

String[] array = string.split(" ", -1);

Both gives same result!

Shree Krishna
  • 8,474
  • 6
  • 40
  • 68
0

Try to use for loop to fill the array like this:

String[] arguments = list.toArray(new String[list.size()]);
for (int i = 0; i < list.size(); i++) {
    arguments[i] = list.get(i);
}

And use foreach to iterate and print elements of the array:

for (String arg: arguments) {
    System.out.println(arg);
}
Abdelhak
  • 8,299
  • 4
  • 22
  • 36