sanclemeteguy
sanclemeteguy

Reputation: 13

How to declare string array of unknown size as input then tokenize

I am trying to declare an array of String which will consist of the input, that is unknown (it depends what text user inputs). I set up a Scanner to read the input then declared a String[] to store the input, and a while loop to go through each line of text and delimit on " ". My question is: How do I set up the array of String to contain the input so I can break it apart into words in the while loop (I can't use ArrayList)

public     class Scramble {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String[] words;

        String line;
        while (in.hasNext()) {
            words.add(line.trim());
        }
    }
}

Upvotes: 0

Views: 175

Answers (1)

Scary Wombat
Scary Wombat

Reputation: 44854

read the whole sentence and do it like this

    Scanner in = new Scanner(System.in);
    String sentence = in.nextLine ();
    String[] words = sentence.split(" ");

    System.out.println(Arrays.toString(words));

Input

this is a test

Output

[this, is, a, test]

Upvotes: 2

Related Questions