java - 为什么我的ArrayList 是空的?

标签 java arraylist java.util.scanner

我正在研究 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/

相关文章:

java - hasNextInt() 和 nextInt() 方法流程

java - 如何使用扫描仪将对象添加到数组列表?

java - 当在我给定的代码中输入整数以外的输入时,它会进入无限循环

java - 如何在java中读取对象(java.lang.Object)

java - 如何高效提取Z3中的子公式(谓词、术语)?

Java回文程序无法运行

java - 比较两个列表共同数据,新数据和旧数据

java - 有没有办法显示正在运行的 JVM 中使用的标志?

java - AP 计算机科学 ArrayList

java - 如何迭代ArrayList中的类?