有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Java的文本文件中的简单列表

我目前正在学习,也是Java编程新手,我有一个关于节点和简单列表的问题

我必须读取两个类似于L1: 1, 5, 8, 4L2: 4, 8, 9, 4的文件,并将它们存储在List而不是Array中。我写了一些代码,但这不是我应该做的,所以如果你能帮助我理解节点和列表,我将非常感激

同样,在读取文件后,必须使用其他两个列表的总和生成另一个列表。这个总和必须与列表的位置一致,所以它应该是这样的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();
        }
    }
}

我希望您能告诉我如何使用列表和节点执行此操作


共 (1) 个答案

  1. # 1 楼答案

    LinkedList{a1}和examples