java - 五个连续数字的最大乘积

标签 java parsing java.util.scanner

我正在尝试将 50 个字符的 String 对象解析为整数。我一直在尝试扫描包含 100 行(每行有 50 位数字)的数据文件并计算数字的总和。

每次我尝试将字符串解析为整数时,调用都会抛出NumberFormatException

这是我到目前为止所拥有的..

{
    long totalSum = 0;
    ArrayList<Long> list = new ArrayList<Long>();

    // Create a new JFileChooser object.
    JFileChooser fileChooser = new JFileChooser(
            "C:\\Users\\Jon\\workspace\\Project Euler\\src");

    // Create an "Open File" Dialog box for
    // the user.
    fileChooser.showOpenDialog(null);

    // Get the file the user selects.
    File inputFile = fileChooser.getSelectedFile();

    try
    {
        Scanner in = new Scanner (inputFile);

        String nextString = "";

        // If the scanner has another token to scan,
        // continue with the loop.
        while (in.hasNext())
        {
            // The next string is the next number of characters
            // that are not seperated by white space.
            nextString = in.next();

            try {

                ing nextNumber = Integer.parseInt(nextString);
                list.add(nextNumber);

            } catch (NumberFormatException e) {
                System.out.println ("NumberFormatException: " + e.getMessage());
            }

        }

        in.close();

在尝试解析之前,我尝试过“修剪” String 对象,但没有任何东西可以修剪。我正在扫描的行中没有任何空白。

以下是我尝试扫描并计算其值的几行内容:

37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629

我已经检查了 API 并在堆栈中进行了相当彻底的搜索。有人知道如何解决这个问题吗?

最佳答案

您的数字太大,无法放入 int 中,范围为 -21474836482147483647。它们也太大了,无法放入 long 中,范围为 -9223372036854775808L9223372036854775807L。如果它不适合数据类型的范围,则会抛出 NumberFormatException

您可能想尝试将数字解析为 double :

double nextNumber = Double.parseDouble(nextString);

但这可能会失去一点精度。 Double 具有 53 位精度,适合大约 16 位数字。使用 double 会失去精度。

要保持精度,请使用BigInteger:

BigInteger nextNumber = new BigInteger(nextString);

一个BigInteger是任意精度并且不会损失任何精度。您可以直接在 BigIntegers 之间使用基本算术和比较。

关于java - 五个连续数字的最大乘积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16309066/

相关文章:

java - 基本 Hibernate/JPA 映射问题

java - 删除帐户、银行程序

java - Java中Http连接池中的连接驱逐策略

java - Java 中的私有(private)辅助方法与公共(public)静态实用程序方法

java - Scanner.findInLine() 大量泄漏内存

java - 比较antlr生成的 token

java - 从 html 文件中获取信息

c - 将多个 C 文件解析为单个 AST 的工具/解析器

java.util.NoSuchElementException : No line found

java - 编写一个循环,直到您在控制台中输入内容为止