猿问

“java.lang.数字格式异常:空字符串”,其中包含一个不为空的字符串

我目前正在课外做一个个人项目,在阅读链接列表中的文本文件时遇到了一些问题。当阅读第一个双打时,我得到一个


java.lang.NumberFormatException: empty String

错误。我在程序中添加了一条打印行,将我试图解析的内容打印成双精度值,并且变量实际上不是空的,实际上是双精度值。


就像我上面说的,我添加了一个打印行来打印出我试图解析为双精度的字符串,这似乎没问题。下面是读入并拆分为我正在打印的数组的字符串:


500.0 % 04/05/2019 % This is paycheck 1 % true % 49.5

我必须将两个字符串解析为双精度值,而我只遇到第一个字符串的问题。当我注释掉第一个正在解析的双精度值时,程序运行没有问题。以下是从运行到程序的完整输出


 *File loading*



    *500.0*


    *Exception in thread "main" java.lang.NumberFormatException: empty String*

        *at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)*

        *at sun.misc.FloatingDecimal.parseDouble(Unknown Source)*

        *at java.lang.Double.parseDouble(Unknown Source)*

        *at fileHandling.readPaycheck(fileHandling.java:194)*

        *at UserMenu.main(UserMenu.java:20)*

问题发生在以下代码行的“将数组拆分为其适当的临时变量”部分中:


payCheckAmount = Double.parseDouble(tempArray[0]);

这是此方法的代码


public void readPaycheck(LinkedList<PayCheck> paycheck) throws IOException {


        // Declare Variables

        Scanner sc = new Scanner(payChecks); // Scanner used to read in from the payChecks text file

        String temp; // A string used to hold the data read in from the file temporarily

        String[] tempArray; // A String array used to temporarily hold data from the text file

        double payCheckAmount; // A double holding the amount of the paycheck

        String paycheckDate; // A string holding the date of the paycheck

        String description; // A string holding a description of the paycheck

        boolean payCheckSplit; // A boolean stating if the paycheck has been split or not

        double amountUnSplit; // A double


        // A while loop that runs while the text file still has data in it

        while (sc.hasNextLine()) {


            // Reading in a new line from the paycheck file

            temp = sc.nextLine();

            // Splitting the line into an array

            tempArray = temp.split(" % ");


        }


    }


慕标5832272
浏览 121回答 1
1回答

呼啦一阵风

您的文本文件可能包含空行。您可以删除文本文件中的新行,更改文本文件的创建方式,或者在阅读文本文件时跳过空行。这是跳过空行的方法:while (sc.hasNextLine()) {&nbsp; &nbsp; &nbsp; &nbsp; String temp = sc.nextLine();&nbsp; &nbsp; &nbsp; &nbsp; if (temp.equals("")) { continue; } // <--- notice this line&nbsp; &nbsp; &nbsp; &nbsp; String[] tempArray = temp.split(" % ");&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(tempArray[0]);&nbsp; &nbsp; &nbsp; &nbsp; // Splitting the array into its appropriate temp variables&nbsp; &nbsp; &nbsp; &nbsp; double payCheckAmount = Double.parseDouble(tempArray[0]);&nbsp; &nbsp; &nbsp; &nbsp; String paycheckDate = tempArray[1];&nbsp; &nbsp; &nbsp; &nbsp; String description = tempArray[2];&nbsp; &nbsp; &nbsp; &nbsp; boolean payCheckSplit = Boolean.parseBoolean(tempArray[3]);&nbsp; &nbsp; &nbsp; &nbsp; double amountUnSplit = Double.parseDouble(tempArray[4]);&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答