【问题标题】:Read empty line in text file读取文本文件中的空行
【发布时间】:2019-12-15 12:50:28
【问题描述】:

如果我想从文本文件中读取文件并将其存储在一个数组中,每一行都会转到正确的数组 这是文本文件

111111,34,24.5,第一行

222222,53,22.0,第二行

333333,,32.0,第三行

44444,22,12.6,

如果由于异常说“缺少标题”或类似的东西,行是空的。 如果数组长度==4然后按顺序显示行但如果长度小于4并且行丢失抛出异常但是当我想放置最后一个数组[3]时会出现错误。看看你是否能看到对你有帮助的错误




import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Itry {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
         String [] splitArray = new String[4];  
         String  line = "";  
         String array1, description;
         int number;
         double price;

        // Total sales
         double total = 0;
         Scanner keyboard = new Scanner (System.in);

        // Allow the user to enter the name of text file that the data is stored in
           System.out.println("This program will try to read data from a text file ");
            System.out.print("Enter the file name: ");
            String filename = keyboard.nextLine();

            Scanner fileReader = null;

            try {
                File Fileobject = new File (filename);
                fileReader  = new Scanner (Fileobject);

                System.out.println("\nTransactions"); 
                System.out.println("================");
                while(fileReader.hasNext())
                {

                    // Contains stock code,Quantity,Price,Description
                    line = fileReader.nextLine();// Read a line of data from text file

                     splitArray = line.split(",");
                    // check to make sure there are 4 parts in splitArray 
                    if(splitArray.length == 4)
                    {
                        // remove spaces
                        splitArray[0] = splitArray[0].trim();
                        splitArray[1] = splitArray[1].trim();
                        splitArray[2] = splitArray[2].trim();
                        splitArray[3] = splitArray[3].trim();

                        // Extract each item into an appropriate
                        // variable
                        try {
                         array1 = splitArray[0];
                         number = Integer.parseInt(splitArray[1]);
                         price = Double.parseDouble(splitArray[2]);
                         description = splitArray[3];
                        // Output item
                        System.out.println("Sold "+String.format("%-5d",  number) +
                                String.format("%-12s", description )+ " at "+"£"+
                                String.format("%-5.2f", price));

                        // Compute total
                        total += number * price;
                        } // end of try
                        catch(NumberFormatException e)
                        {
                        System.out.println("Error: Cannot convert to number");
                        }

                  } //end of if 

                     else if (splitArray[0].length()<1) {
                    try {   splitArray[0] = splitArray[0].trim();
                        System.out.println("  Title is missing "+" "+splitArray[1] +""+splitArray[2]+"");
                    }

                    catch(NumberFormatException e)
                    {
                    System.out.println("Error: Cannot convert to number");
                    }
                     }
                     else   if (splitArray[1].length()<=1) {
                            try {   splitArray[1] = splitArray[1].trim();
                            System.out.println(splitArray[0]+" "+" here is missing " +""+splitArray[2] );

                        }
                        catch(NumberFormatException e)
                        {
                        System.out.println("Error: Cannot convert to number");
                        }}

                     else   if (splitArray[2].length()<=1) {
                            try {   splitArray[2] = splitArray[2].trim();
                            System.out.println(splitArray[0]+" "+splitArray[1] +""+" here is missing "+splitArray[3]);

                            }
                        catch(NumberFormatException e)
                        {
                        System.out.println("Error: Cannot convert to number");
                        }}

                            else    if (splitArray[3].length()<=1) {
                            try {   splitArray[3] = splitArray[3].trim();
                            System.out.println(splitArray[0]+" "+splitArray[1] +""+splitArray[2]+"title is missing");
                        }

                        catch(NumberFormatException e)
                        {
                        System.out.println("Error: Cannot convert to number");
                        }}
                }//end of while
                System.out.printf("\nTotal sales: £"+String.format("%-6.2f", total));

             }// end of try block
            catch (FileNotFoundException e) 
            {
                System.out.println("Error - File does not exist");          
            }
    }

}


【问题讨论】:

  • 您对 splitarray[3] 的引用在 else off of if length 为 4,因此在您的最后一个示例行中,长度实际上是 3,并且引用 [3] 会给您一个错误。将 splitArray[3].length()= 4 && splitArray[3].length()
  • 非常感谢,我现在就试试
  • @kila - 我希望解决方案对你有用。不要忘记接受答案,以便将来的访问者也可以放心地使用该解决方案。检查meta.stackexchange.com/questions/5234/… 了解如何操作。如有任何疑问/问题,请随时发表评论。

标签: java arrays file text is-empty


【解决方案1】:

你可以这样做:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] splitArray = new String[4];
        String line = "";
        String array1, description;
        int number;
        double price;

        // Total sales
        double total = 0;
        Scanner keyboard = new Scanner(System.in);

        // Allow the user to enter the name of text file that the data is stored in
        System.out.println("This program will try to read data from a text file ");
        System.out.print("Enter the file name: ");
        String filename = keyboard.nextLine();

        Scanner fileReader = null;

        try {
            File Fileobject = new File(filename);
            fileReader = new Scanner(Fileobject);

            System.out.println("\nTransactions");
            System.out.println("================");
            int count = 1;
            while (fileReader.hasNext()) {

                // Contains stock code,Quantity,Price,Description
                line = fileReader.nextLine();// Read a line of data from text file
                try {
                    if (line != null && line.length() > 0) {
                        splitArray = line.split(",");

                        // check to make sure there are 4 parts in splitArray
                        if (splitArray.length == 4) {
                            // remove spaces
                            splitArray[0] = splitArray[0].trim();
                            splitArray[1] = splitArray[1].trim();
                            splitArray[2] = splitArray[2].trim();
                            splitArray[3] = splitArray[3].trim();

                            // Extract each item into an appropriate variable
                            try {
                                array1 = splitArray[0];
                                number = Integer.parseInt(splitArray[1]);
                                price = Double.parseDouble(splitArray[2]);
                                description = splitArray[3];
                                // Output item
                                System.out.println(
                                        "Sold " + String.format("%-5d", number) + String.format("%-12s", description)
                                                + " at " + "£" + String.format("%-5.2f", price));

                                // Compute total
                                total += number * price;
                            } catch (NumberFormatException e) {
                                System.out.println("Error in line#" + count + ": insufficient/invalid data");
                            }
                        } else {
                            throw new IllegalArgumentException(
                                    "Error in line#" + count + ": insufficient/invalid data");
                        }
                    } else {
                        throw new IllegalArgumentException("Line#" + count + " is empty");
                    }
                } catch (IllegalArgumentException e) {
                    System.out.println(e.getMessage());
                }

                count++;
            } // end of while
            System.out.printf("\nTotal sales: £" + String.format("%-6.2f", total));
        } catch (FileNotFoundException e) {
            System.out.println("Error - File does not exist");
        }
    }
}

示例运行:

This program will try to read data from a text file 
Enter the file name: data2.txt

Transactions
================
Sold 34   Apple        at £24.50
Line#2 is empty
Sold 53   Mango        at £22.00
Line#4 is empty
Error in line#5: insufficient/invalid data
Line#6 is empty
Error in line#7: insufficient/invalid data

Total sales: £1999.00

data2.txt 的内容:

111111,34,24.5,Apple

222222,53,22.0,Mango

333333,,32.0,Orange

44444,22,12.6,

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多