mardi 12 juillet 2016

Read Strings saparated by newline using BufferedReader into a String array

I've read number of such questions but they are all about reading inputs from a txt file. I want to read input from user and not from the file.

I've input like following:

6   //number of total Strings to store in array 
babu   
anand
rani    
aarti
nandu
rani

I've tried the following code to take such input in a String array:

    int n = in.nextInt();    // n= 6 here
    String[] s = new String[n];   //String array of size 6 here
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    try{
         s = br.readLine().split("\s");
    }
    catch(Exception e){
        System.out.println(e);
    } 

Is the regex provided to the split() is correct or not? What I'm missing here? If this is not correct approach than what should I do for this problem?

Aucun commentaire:

Enregistrer un commentaire