JAVA。从文件读取,返回BigInteger值

时间:2019-02-26 12:06:31

标签: java

我遇到了一个问题。我有一个代码,应该从文件中读取BigInteger并运行Collat​​z假设检验。问题是,我想做一个将值返回到主代码的方法。但是,此代码不返回值。如果我将print语句放入while循环中,它将起作用。但是,当我尝试返回值或将打印语句放在while循环之外时,它无法编译。可能是什么问题?预先谢谢你。

public static BigInteger readFile() {
    File file = new File ("C:\\number.txt");
    try {

        Scanner scan = new Scanner(file);
        while (scan.hasNext()) {
            BigInteger n = scan.nextBigInteger();
        }
        scan.close();
    } catch (Exception e) {
        e.printStackTrace();
    } 
    return n;   
}

1 个答案:

答案 0 :(得分:0)

替换为:

public static BigInteger readFile() {
    File file = new File ("C:\\number.txt");
    BigInteger n = null;
    try {

        Scanner scan = new Scanner(file);
        while (scan.hasNext()) {
            n = scan.nextBigInteger();
        }
        scan.close();
    } catch (Exception e) {
        e.printStackTrace();
    } 
    return n;   
}