-2

如果我有以下文本文件:

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
            }

`

4

1 回答 1

0

我已经list1成为一个二维数组,它将每一行作为它的行。我正在存储号码。的每一行的元素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 
于 2014-11-24T03:09:22.417 回答