我正在学习,而且我是Java编程的新手,我对节点和简单列表有疑问。
我必须阅读两个看起来像L1: 1, 5, 8, 4
和L2: 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();
}
}
}
我希望您能告诉我如何使用列表和节点执行此操作。