我有一个 ArrayList 并且我希望它读取并总计文件中的数字,但它只输出文件中的最后一个数字,它们都在不同的行等。
Here is my code, thanks in advance:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListOfNumbers {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
Scanner Scan = new Scanner (new File("numbers.txt"));
int sumOf = 0;
for(int i=0; i < list.size(); i++){
sumOf = sumOf + list.get(i);
}
//while scanning add sum to ArrayList List
while (Scan.hasNext())
{
sumOf = Scan.nextInt();
list.add(sumOf);
}
//print the array list
System.out.println(sumOf);
Scan.close();
}
}