Hello people.
My aim is to assing an array with words read from system.in in a single entry.
So if the users enters "Hello there"
i will have
0,Hello
1,Therre

I have managed to achieve this with the following piece of code.

import java.util.Scanner;


public class mein 
{
	public static void main(String[] args)
	{
		String[] searchArray = {"yes","no"};
		
		System.out.println("Enter Key");
		
		Scanner getKey = new Scanner(System.in);
		while (getKey.hasNext())
		{
			for (int i=0; i<2; i++)
			{
			searchArray[i] = getKey.next();
			System.out.println(searchArray[i]);
			}
		}
	}
}

All fine till here.
What if i want to extract 3 words ? even worse what if i want to extract unknown number of words ?

I Tried the following code as well but faced errors.

import java.util.Scanner;


public class mein 
{
	public static void main(String[] args)
	{
		String[] searchArray = null;
		
		System.out.println("Enter Key");
		
		Scanner getKey = new Scanner(System.in);
		while (getKey.hasNext())
		{
			for (int i=0; i<searchArray.length; i++)
			{
			searchArray[i] = getKey.next();
			System.out.println(searchArray[i]);
			}
		}
	}
}

Of course since the array is null there'is no length!
What could i do ?
Any ideas ?

Hi,
can read the line to simple String attribute. There are some String methods to work with it. You can use method - split("\\s") - where inside brackets there is regular expression determines how to split the string into peaces. in this case \\s means white space. Check som java tutorial about regex . So in your case try something like String text = getKey.next(); searchArray = text.split("\\s");

Could you please implement it ?
How would the code look ?

I got a bit confugsed with regex.

put into your while loop:
searchArray = getKey.next().split("\\s");
then you will have your array filled by the seperated words

Sorry but this pops up an error

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.