Question

How I can add elements to a list from a input in java.

Like if i put:

Scanner reader = new Scanner("a,b,c,d,e);

I want to Have it like String[] a = {a,b,c,d,e];

Using any Scanner Methods with whiles , Really i am little bit lost

Sorry for my English( is not my main language)

Was it helpful?

Solution 2

To add inputs to list like this

import java.util.ArrayList;
import java.util.Scanner;

 public class StackOverflow {

  public static void main(String[] args) {
     ArrayList<String> inputList = new ArrayList<String>();

     Scanner reader = new Scanner(System.in);
     String input = reader.nextLine();
     inputList.add(input);

     while (!input.equals("null")) {
         input = reader.nextLine();
         inputList.add(input);
     }
  }

 }

OTHER TIPS

If you know how many input items you are going to accept, declare an array before you start the input, then put each input into the array until you run out of array space.

The better way to do this is to use ArrayList:

ArrayList<String> inputList = new ArrayList<String>();

Using a Scanner, you can retrieve the next input (if you want an entire line, use reader.nextLine() to get that string. I'd suggest storing that in a local variable temporarily so you can examine it if you need to (you'll need some sort of termination sentinel or use hasNextLine() to see if there is more to read.

If you then need to return as an array, ArrayList has a toArray() method you can call.

This should work, the default token used by Scanner is whitespace characters.

public String[] getStringArray(String input, int arraySize) {

     String[] stringArray = new String[arraySize];
     Scanner s = new Scanner(input);

     for (int i = 0; s.hasNext(); i++) {
         stringArray[i] = s.next();
     }

     s.close();

     return stringArray;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top