0

我目前正在学习,而且我是 Java 编程新手,我对节点和简单列表有疑问。

我必须阅读两个看起来像这样的文件,L1: 1, 5, 8, 4并将L2: 4, 8, 9, 4它们存储在一个ListArray. 我写了一些代码,但这不是我应该做的,所以如果你能帮助我理解节点和列表,我会非常感激。

同样在读取文件后,必须生成另一个列表,其中包含其他两个列表的总和。这个总和必须与列表的位置,所以它应该看起来像这样L3: 5, 13, 17, 8

这是我使用的代码:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;

public class Read {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        FileReader fr, fr2;
        try {
            fr = new FileReader(new File("list1.txt"));
            BufferedReader br = new BufferedReader(fr);
            String line = br.readLine();

            fr2 = new FileReader(new File("list2.txt"));
            BufferedReader br2 = new BufferedReader(fr2);
            String line2 = br2.readLine();

            StringTokenizer st = new StringTokenizer(line, ", ");
            int dimension = st.countTokens();
            int sum = 0;
            int sum2 = 0;
            int total = 0;

            int[] arrNum = new int[dimension];

            while (st.hasMoreTokens()) {
                System.out.print("List 1: ");
                for (int i = 0; i < arrNum.length; i++) {
                    arrNum[i] = Integer.parseInt(st.nextToken());
                    System.out.print(arrNum[i] + ", ");
                    sum += arrNum[i];
                }
            }
            System.out.println("\nThe sum of the first list is: " + sum + "\n");

            StringTokenizer st2 = new StringTokenizer(line2, ", ");
            int dimension2 = st2.countTokens();

            int[] arrNum2 = new int[dimension2];

            while (st2.hasMoreTokens()) {
                System.out.print("List 2: ");
                for (int j = 0; j < arrNum2.length; j++) {
                    arrNum2[j] = Integer.parseInt(st2.nextToken());
                    System.out.print(arrNum2[j] + ", ");
                    sum2 += arrNum2[j];
                }
            }
            System.out.println("\nThe sum of the second list is: " + sum2);

            total = sum + sum2;
            System.out.println("\nThe sum of the lists are: " + total);

            br.close();
            br2.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

我希望你能告诉我如何使用列表和节点来做到这一点。

4

1 回答 1

0

请参阅LinkedList 文档示例

于 2012-07-18T21:59:31.040 回答