Java ArrayList未正确读入
我有一个ArrayList&我想让它读入并合计文件中的数字,但它只输出文件中的最后一个数字,它们都在不同的行上,等等Java ArrayList未正确读入,java,Java,我有一个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 { p
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();
}
}
这是我的代码,提前感谢:
导入java.io.File;
导入java.io.FileNotFoundException;
导入java.util.ArrayList;
导入java.util.Scanner;
公共类ArrayListOfNumbers{
公共静态void main(字符串[]args)引发FileNotFoundException{
ArrayList=新建ArrayList();
增加第(1)款;
扫描仪扫描=新扫描仪(新文件(“numbers.txt”);
int-sumOf=0;
对于(int i=0;i
您正在打印的是sumOf
而不是列表。当然,这是一个单一的数字
此外,在对数字求和之前,您应该先阅读数字。您正在打印的是
sumOf
而不是列表。当然,这是一个单一的数字
此外,在对数字进行求和之前,您应该先阅读数字。在阅读数字之前,您正在对列表中的数字进行求和 所以像这样移动你的循环:
//while scanning add sum to ArrayList List
while (Scan.hasNext())
{
int number = Scan.nextInt();
list.add(number);
}
int sumOf = 0;
for(int i=0; i < list.size(); i++){
sumOf = sumOf + list.get(i);
}
//扫描时将总和添加到ArrayList列表
while(Scan.hasNext())
{
int number=Scan.nextInt();
列表。添加(编号);
}
int-sumOf=0;
对于(int i=0;i
在阅读数字之前,您正在对列表中的数字进行求和
所以像这样移动你的循环:
//while scanning add sum to ArrayList List
while (Scan.hasNext())
{
int number = Scan.nextInt();
list.add(number);
}
int sumOf = 0;
for(int i=0; i < list.size(); i++){
sumOf = sumOf + list.get(i);
}
//扫描时将总和添加到ArrayList列表
while(Scan.hasNext())
{
int number=Scan.nextInt();
列表。添加(编号);
}
int-sumOf=0;
对于(int i=0;i
逐行阅读,适当命名变量。从文件中读取后,迭代列表并求和
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
逐行读取,适当地命名变量。从文件中读取后,迭代列表并求和
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}