0

I am trying to parse a 50 character String object to an integer. I have been trying to scan in a data file containing 100 lines (each with a 50 digit number) and compute the sum of the numbers.

Every time I try to parse the String as an integer the call throws a NumberFormatException.

Here's what I have so far..

{
    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();

I have tried "trimming" the String object before attempting to parse, but there wasn't anything to trim. There isn't any white space in the lines that I am scanning in.

Here are a few lines of what I am trying to scan in and compute the value of:

37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629

I've check the API and searched quite thoroughly through the Stack. Anyone know how to get around this?

4

1 回答 1

2

您的数字太大而无法放入int, 范围为-2147483648through 2147483647。它们也太大了long,无法放入具有范围的范围-9223372036854775808L9223372036854775807L。如果它不适合数据类型的范围,则NumberFormatException抛出 a。

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

double nextNumber = Double.parseDouble(nextString);

但这可能会失去一些精度。ADouble具有 53 位精度,适用于大约 16 位。你会失去精确度double

要保持精度,请使用BigInteger

BigInteger nextNumber = new BigInteger(nextString);

ABigInteger是任意精度,不会丢失任何精度。您可以直接在BigIntegers.

于 2013-04-30T21:19:40.083 回答