tags:

views:

98

answers:

3

I want to make something read from inputstream to store in an int[] when I type "read 1 2 3 4". what should i do?

I do not know the size of the array, everything is dynamic...

Here is the current code:

BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
String line = stdin.readLine();
StringTokenizer st = new StringTokenizer(line);
String command = st.nextToken();

if (command.equals("read")) {
   while (st.nextToken() != null) {
       //my problem is no sure the array size
   }
}
A: 

You either use a storing structure with nodes, that you can easily append one after another, or, if you really must use arrays, you need to allocate space periodically, as it becomes necessary.

Luis Miguel
+2  A: 

You need to build something to parse the input stream. Assuming it's literally as uncomplex as you've indicated the first thing you need to do is get the line out of the InputStream, you can do that like this:

// InputStream in = ...;

// read and accrue characters until the linebreak
StringBuilder sb = new StringBuilder();
int c;
while((c = in.read()) != -1 && c != '\n'){
    sb.append(c);
}

String line = sb.toString();

Or you can use a BufferedReader (as suggested by comments):

BufferedReader rdr = new BufferedReader(new InputStreamReader(in));
String line = rdr.readLine();

Once you have a line to process you need to split it into pieces, then process the pieces into the desired array:

// now process the whole input
String[] parts = line.split("\\s");

// only if the direction is to read the input
if("read".equals(parts[0])){
    // create an array to hold the ints
    // note that we dynamically size the array based on the
    // the length of `parts`, which contains an array of the form
    // ["read", "1", "2", "3", ...], so it has size 1 more than required
    // to hold the integers, thus, we create a new array of
    // same size as `parts`, less 1.
    int[] inputInts = new int[parts.length-1];

    // iterate through the string pieces we have
    for(int i = 1; i < parts.length; i++){
         // and convert them to integers.
        inputInts[i-1] = Integer.parseInt(parts[i]);
    }
}

I'm sure some of these methods can throw exceptions (at least read and parseInt do), I'll leave handling those as an exercise.

Mark E
You could reduce some work by using the BufferedReader's readLine() method.
shinkou
@shinkou, sure, it's not entirely important, but I'll humor you.
Mark E
A: 

Parse-out the data and keyword from your string then push it into something like this:

public static Integer[] StringToIntVec( String aValue )
{

    ArrayList<Integer> aTransit = new ArrayList<Integer>();

    for ( String aString : aValue.split( "\\ ") )
    {
        aTransit.add( Integer.parseInt( aString ) );

    }

    return aTransit.toArray( new Integer[ 0 ] );

}
Sackers