How to add elements from string added from console to a list in java -


how can add elements list input in java.

like if put:

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

i want have string[] = {a,b,c,d,e];

using scanner methods whiles , little bit lost

sorry english( not main language)

share|improve question
    
you want use string.split(). see here example: tutorialspoint.com/java/java_string_split.htm after read string scanner, split on comma. – dcp apr 22 '14 @ 0:48
up vote 0 down vote accepted

to add inputs list 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);      }   }   } 
share|improve answer

if know how many input items going accept, declare array before start input, put each input array until run out of array space.

the better way use arraylist:

arraylist<string> inputlist = new arraylist<string>(); 

using scanner, can retrieve next input (if want entire line, use reader.nextline() string. i'd suggest storing in local variable temporarily can examine if need (you'll need sort of termination sentinel or use hasnextline() see if there more read.

if need return array, arraylist has toarray() method can call.

share|improve answer

this should work, default token used scanner whitespace characters.

public string[] getstringarray(string input, int arraysize) {       string[] stringarray = new string[arraysize];      scanner s = new scanner(input);       (int = 0; s.hasnext(); i++) {          stringarray[i] = s.next();      }       s.close();       return stringarray; } 
share|improve answer

your answer

 
discard

posting answer, agree privacy policy , terms of service.

not answer you're looking for? browse other questions tagged or ask own question.

Comments