如果我有以下文本文件:
5 -5 -4 -3 -2 -1
6 -33 -22 -11 44 55 66
(第一个#行是列表的长度)
如何逐行读取文件,然后读取每行中的整数以创建2个列表?
所需的节目输出:
list1 = [-5,-4,-3,-2,-1]
list2 = [-33,-22,-11,44,55,66]
以下是我能够完成一行但我不知道如何修改它以继续阅读这些行。
import java.util.*;
import java.io.*;
import java.io.IOException;
public class Lists
{
public static void main(String[] args) throws IOException // this tells the compiler that your are going o use files
{
if( 0 < args.length)// checks to see if there is an command line arguement
{
File input = new File(args[0]); //read the input file
Scanner scan= new Scanner(input);//start Scanner
int num = scan.nextInt();// reads the first line of the file
int[] list1= new int[num];//this takes that first line in the file and makes it the length of the array
for(int i = 0; i < list1.length; i++) // this loop populates the array scores
{
list1[i] = scan.nextInt();//takes the next lines of the file and puts them into the array
}
`
答案 0 :(得分:0)
我已将list1
设为2d数组,其中每行都是行。我正在存储号码。每个list1
行的元素到另一个数组listSizes[]
而不是代码中使用的num
。如果您需要在2个数组中阅读所有行,您可以轻松地从list1
移动它。
int listSizes[] = new int[2];
int[][] list1= new int[2][10];
for(int j = 0; scan.hasNextLine(); j++) {
listSizes[j] = scan.nextInt();
for(int i = 0; i < listSizes[j]; i++)
{
list1[j][i] = scan.nextInt();
}
}
for(int j = 0; j < 2; j++) {
for(int i = 0; i < listSizes[j]; i++)
{
System.out.print(list1[j][i] + " ");
}
System.out.println();
}
-5 -4 -3 -2 -1
-33 -22 -11 44 55 66