如何读取一行中每个 int 的 .txt 文件并存储到数组?
How to read a .txt file for each int on a line & storing to array?
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
只需替换您的行:
System.out.print(numbers[1]);
与:
for (int i = 0; i < numbers.length; i++)
System.out.print(numbers[i] + " ");
System.out.println();
告诉我它是如何工作的。
您需要通过添加另一个循环来修改代码:
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();
}
因为,numbers[1] 只会打印索引 1 处的值。
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
只需替换您的行:
System.out.print(numbers[1]);
与:
for (int i = 0; i < numbers.length; i++)
System.out.print(numbers[i] + " ");
System.out.println();
告诉我它是如何工作的。
您需要通过添加另一个循环来修改代码:
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();
}
因为,numbers[1] 只会打印索引 1 处的值。