你需要構建一些東西來解析輸入流。假設它的字面意思是不復雜的,你已經表明你需要做的第一件事就是讓行出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]);
}
}
我小號這些方法中的一些可能會拋出異常(至少有read
和parseInt
),我將把這些作爲練習來處理。
檢查這個[示例](http://www.ensta.fr/~diam/java/online /notes-java/data/arrays/arrays.html)。 – Emil 2010-10-22 05:36:23