How to take a space separated character sequence as input in java without knowing number of characters input [closed]

Tags: ,



I wish to read a space-separated character sequence in java but the number of characters to be input is not known. For example, this is the input 12 34 e 2 a 9 d

How do I store each of these in a list?

I tried using:

while(scan.hasNext())
    list.add(scan.next().charAt(0)); // list is an ArrayList<Character>

Can someone tell me why this doesn’t work? (I am having a hard time understanding what method hasNext() really does.

Answer

If you want the words, you can use String.trim().split(" "). This will remove leading and trailing whitespaces, and return an array of words that were seperated by whitespaces.

You can also use Scanner sc = new Scanner(<your file>).useDelimiter(" "); to configure your scanner to split the text into tokens using the spaces as breaks.

Scanner.hasNext() returns a boolean value depending on whether there is a next token or not.

String.charAt(0) returns the first character of the string. If you want to read every letter, you’ll have to loop through each word using String.charAt(<loop variable>)



Source: stackoverflow