Apoorv singhai Apoorv singhai - 2 months ago 8x
Java Question

Create a dynamic string array in java? the inputs are seprated by whitespaces

I know the number of inputs but dont know the length of each input string, inputs are in the form that are separated by space character.
I want to fill each input in an string array.

Scanner kb=new Scanner(System.in);
//System.out.print("Input\n Number of teams: ");
//int N=kb.nextInt();
System.out.println("Input team names: ");
String Na=kb.nextLine();
String[] names=Na.split(" ");
System.out.print("Array :"+names[2]);

Its the code i created using split() method
But if i uncomment the 2 lines nextLine method skips input it skips the input

Scanner kb=new Scanner(System.in);
System.out.print("Input\n Number of teams: ");
int N=kb.nextInt();
System.out.print("Input team names: ");
String Na=kb.nextLine();
String[] names=Na.split(" ");
System.out.print("Array :"+names[2]);

This worked !


You can use an ArrayList to store your strings.

ArrayLists don't have a specified upper limit on the number of objects they hold, and so can be resized on the fly as you add more objects. This is what it would look like in practice:

ArrayList<String> stringList = new ArrayList<>();
while (hazMoarStrings) {

Edit: Since the user provides a String separated by whitespace, you actually don't need to create your own array!

String.split() will do the job for you!

String myInput = getUserInput();
String delimiter = " "; // what the user separated the words by
String[] tokens = myInput.split(delimiter);

P.S. Read up on Regular Expressions for more advanced usage of the String.split() method