我正在研究 Project Euler 问题 13。( https://projecteuler.net/problem=13 ) 文件“Large_Num_List.txt”是由 Euler 项目提供的列表,每个数字独占一行,每个数字的开头和结尾都有引号线。语句 bial.isEmpty() 返回 true。为什么会发生这种情况? (我怀疑是因为这是我第一次使用扫描仪读取文本文件。)
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
import java.math.BigInteger;
import java.util.Iterator;
public class LargeSumTwo
{
public static void main(String[] args)
{
ArrayList<BigInteger> bial = new ArrayList<BigInteger>();
File file = new File("Large_Num_List.txt");
try
{
Scanner scan = new Scanner(file);
while(scan.hasNextBigInteger())
{
bial.add((BigInteger) scan.nextBigInteger());
}
scan.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println(bial.isEmpty());
BigInteger answer = new BigInteger("0");
Iterator<BigInteger> iter = bial.iterator();
while(iter.hasNext())
{
answer.add(iter.next());
}
System.out.println(answer);
}
}
最佳答案
您需要先去掉引号。仅当 Scanner
可以解析 BigInteger
时,hasNextBigInteger()
才会返回 true
。数字周围的引号将导致 hasNextBigInteger()
返回 false
。
JavaDoc:http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextBigInteger%28%29
关于java - 为什么我的ArrayList 是空的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28132556/