读输入为数组

时间:2010-10-22 02:12:40

标签: java input

当我输入“read 1 2 3 4”时,我想从输入流中读取一些内容存储在int []中。我该怎么办?

我不知道数组的大小,一切都是动态的......

以下是当前代码:

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
   }
}

3 个答案:

答案 0 :(得分:1)

您需要构建一些东西来解析输入流。假设它确实是非复杂的,因为你已经表明你需要做的第一件事是从InputStream中取出,你可以这样做:

// 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();

或者您可以使用BufferedReader(根据评论建议):

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

一旦你有一条线要处理,你需要将它分成几块,然后将这些块处理成所需的数组:

// 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]);
    }
}

我确信其中一些方法可以抛出异常(至少readparseInt),我会将这些作为练习处理。

答案 1 :(得分:0)

你要么使用带有节点的存储结构,你可以轻松地一个接一个地附加,或者,如果你真的必须使用数组,你需要定期分配空间,因为它是必要的。

答案 2 :(得分:0)

从字符串中解析数据和关键字,然后将其推送到以下内容:

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 ] );

}