public class assignment2
{
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
FileInputStream fstream = new FileInputStream("assignment2.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
String[] numbers = strLine.split(" ");
System.out.print(numbers[1]);
}
//Close the input stream
br.close();
}
}
我希望代码会将String []数字打印为 1 0 10
我得到的结果是00371010
请注意输入文件的格式如下:
1 0 10
2 0 9
3 3 5
4 7 4
5 10 6
6 10 7
答案 0 :(得分:4)
只需更换你的行:
System.out.print(numbers[1]);
使用:
for (int i = 0; i < numbers.length; i++)
System.out.print(numbers[i] + " ");
System.out.println();
让我知道它是如何运作的。
答案 1 :(得分:1)
您需要通过添加另一个循环来修改代码:
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileInputStream fstream = new FileInputStream("assignment2.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null){
// Print the content on the console
System.out.println (strLine);
String[] numbers = strLine.split(" ");
for (String num : numbers){
System.out.print(num + " ");
}
System.out.println("\n");
}
//Close the input stream
br.close();
}
因为,数字[1]只会打印索引1处的值。