简体   繁体   English

为什么我的ArrayList为空?

[英]Why is my ArrayList Empty?

I am working on Project Euler problem 13. ( https://projecteuler.net/problem=13 ) The file "Large_Num_List.txt" is the list provided by the project Euler with each number on its own line with a quote mark at the beginning and end of each line. 我正在研究Euler项目问题​​13。( https://projecteuler.net/problem=13 )文件“ Large_Num_List.txt”是项目Euler提供的列表,每个数字在其自己的行上带有引号,每行的开始和结束。 The statement bial.isEmpty() returns true. 语句bial.isEmpty()返回true。 Why is this happening? 为什么会这样呢? (I suspect because this is my first time using Scanner to read a text file.) (我怀疑是因为这是我第一次使用扫描仪读取文本文件。)

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);
  }
}

You need to strip the quotes first. 您需要先去除引号。 hasNextBigInteger() will only return true if Scanner can parse a BigInteger . 如果Scanner可以解析BigIntegerhasNextBigInteger()将仅返回true The quotes around the numbers will cause hasNextBigInteger() to return false . 数字周围的引号将导致hasNextBigInteger()返回false

JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextBigInteger%28%29 JavaDoc: http : //docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextBigInteger%28%29

Should you add BigInteger in this way: 您是否应该以这种方式添加BigInteger:

while(iter.hasNext())
{
  answer = answer.add(iter.next());
}

as BigDecimal numbers are immutable? 因为BigDecimal数是不可变的?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM