读取文件时的 Java 数据验证无法正常工作

标签 java file validation file-io

我是编程新手,我正在尝试创建一个可以从文件读取数据并将数据输出到控制台的程序。

我还尝试检查每一行数据以确保其有效。

每行应有 5 个部分:标题、作者、价格、出版商和 isbn。 如果缺少其中任何一个,我需要让程序输出到控制台,然后计算有多少有效和无效条目,并将其输出到最后的表中。 下面是我到目前为止编写的代码,有人可以建议我可以使其正常工作的方法吗?

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.NumberFormat;

public class libaryAssignment {

public static void main(String[] args) {

    String[] title = new String[100];
    String[] author = new String[100];
    double[] price = new double[100];
    String[] publisher = new String[100];
    String[] isbn = new String[100];
    int invalidcount = 0;
    int count = 0;
    String line = "";

    Scanner scan = new Scanner (System.in);

    String[] splitLine = new String[100];


    File Fileobject = new File ("valid-invalid.txt");
    if (!Fileobject.exists())
    {
        System.out.println("Error - File does not exist");
        System.exit(0); }

    try {
        Scanner fileReader = new Scanner (Fileobject);

        //Formatting for the outputted data so that is lined up and looks presentable.
        //The % and the number next to it ensure that text is lined up appropriately.
        System.out.println();
        System.out.format("%-20s %5s %16s %15s %13s", "Title", "Author", "Price", "Publisher", "ISBN");
        System.out.println();
        System.out.format("%-20s %5s %16s %15s %13s", "=====", "=====", "=====", "=========", "====");
        System.out.println();



        while(fileReader.hasNext())
        {
            line = fileReader.nextLine();

            String [] splitArray = line.split("-");

            boolean validline = true;

            if(splitArray.length == 5)

                splitArray[0] = splitArray[0].trim();
                splitArray[1] = splitArray[1].trim();
                splitArray[2] = splitArray[2].trim();
                splitArray[3] = splitArray[3].trim();
                splitArray[4] = splitArray[4].trim();

                if(splitArray[0].isEmpty()) {
                    validline = true;
                    System.out.println("Title is missing"); }
                if(splitArray[1].isEmpty()) {
                    validline = true;
                    System.out.println("Author is missing" + line); }
                if(splitArray[2].isEmpty()) {
                    validline = true;
                    System.out.println("Price is missing" + line); }
                else {
                    Double.parseDouble(splitArray[2]);
                }
                if(splitArray[3].isEmpty()) {
                    validline = true;
                    System.out.println("Publisher is missing" + line); }
                if(splitArray[4].isEmpty()) {
                    validline = true;
                    System.out.println("ISBN is missing" + line); }     


                if (validline == true) {
                    title[count]=splitArray[0];
                    author[count]=splitArray[1];
                    price[count]=Double.parseDouble(splitArray[2]);
                    publisher[count]=splitArray[3];
                    isbn[count]=splitArray[4];

                    count++; }
        else {
            invalidcount++; 
        } 
        }
    }
        catch (FileNotFoundException e) {
            System.out.println("File does not exist");
        }
        catch (NumberFormatException e) {
            System.out.println("Error");
        }

        //Declaring the "PRETTY_PRINT" which does the formatting for the user data that will be output.
        final String PRETTY_PRINT = "%-20s %5s %12.2f %15s %13s";

        //Declaring the Minimum and Maximum variables.
        double minCost = price[0];
        double maxCost = price[0];


        /*for loop which declares "j" and increments it by 1. 
        /*If "j" is less than the books then it increments "j" by one.
         */
        for (int j = 0; j < count; j++) {


            //this is saying if the price is less than "minCost" then the minCost = price. Vice versa for "maxCost".
            if (price[j] < minCost) {
                minCost = price[j];
            }

            if (price[j] > maxCost) {
                maxCost = price[j];
            }

        }

        //Declaring the variable "totalPrice".
        double totalPrice = 0.0;

        //for loop which takes the variable "i" and sets it at 0.
        //Then looks to see if its less than books and increments it by. 
        for (int i = 0; i < count; i++) {

            //this is totalPrice = totalPrice + price to give us the total cost of a book.
            totalPrice += price[i];

            //prints out the user data and inputs into a table.
            System.out.println(String.format(PRETTY_PRINT, title[i], author[i], price[i], publisher[i], isbn[i]));
        }

        //outputs the final table which shows the min and max cost of a book using the variables "minCost" and "maxCost".
        //outputs the average price by dividing by the total price.
        //outputs the number of books by simply displaying the book variable.
        NumberFormat money = NumberFormat.getCurrencyInstance();
        System.out.println();
        System.out.println("Totals");
        System.out.println("--------------------------");
        System.out.println("Total number of books: "+ count);
        System.out.println("Total cost of a book: " + money.format(totalPrice));
        System.out.println("Minimum cost of a book: " + money.format(minCost));
        System.out.println("Maximum cost of a book: " + money.format(maxCost));
        System.out.println("Average cost of a book: " + money.format(totalPrice / count));
        System.out.println("Total number of valid books: " + count);
        System.out.println("Total number of invalid books: " + invalidcount);

        //closing the scanner
        scan.close();



    }

}

下面是我的测试数据,其中包含无效和有效的条目,我用它来测试我的代码是否正常工作。

Learning Java - William Lane -12.00 - Wiley - 0811234561

William Stalling - 25.00 - Prentice Hall - 1304086641

OOP programming - Graham Winter - 32.50 - O'Reilly - 0471974555

Windows XP Unwired - Wei Meng Lee - 24.95 - O'Reilly - 0596005369

Programming with Perl - - 19.99 - Wiley - 0476887021

Multimedia Comms - Fred Halsall - 53.99 - Addison Wesley - 0201398184

Guide to Networks - Tamara Dean - 34.50 - Course Tech - 1439055661

A Guide to MySQL -Paul Barry - - Thomson - 1418834351

CCDA Exam Guide - Anthony Bruno - 49.95 - Cisco Press - 0735700745

Perl and CGI - Elizabeth Castro - 99.50 - - 0201735687

802.11 Security - Jon Edney - 68.99 - Addison Wesley - 0321136209

Web Design - Hoel Sklar - 9.99 - Course Tech -

Large Scale LANs - Kevin Dooley - 39.00 - O'Reilly - 0596001509

HTML and JavaScript: David Gast - 12.00 - Wiley 0471383661

Database and Web - Simon Burns - 12Q - Perasons - 0559000412

Wireless Hacks - Rob Weeks - 29.50 - O'Reilly - 0596101442

Trace of Guilt - Neil Barret - 5.99 - Corgi Books - 055X215001

最佳答案

更正括号后,代码的输出如下。

Totals

Total number of books: 6
Total cost of a book: $177.93
Minimum cost of a book: $12.00
Maximum cost of a book: $53.99 Average cost of a book: $29.66 Total number of valid books: 6 Total number of invalid books: 0

这是预期的吗?

关于读取文件时的 Java 数据验证无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47610740/

相关文章:

python - 从元组列表中写入由换行符分隔的不同列中的文本文件

ruby-on-rails - Rails 3 : creating a validation with :if statement

php - Laravel 5.2 带有 where 子句的唯一验证无法按预期工作

java - 无法从 System.in InputStreamReader 返回结果

java - KeyPress 处理程序不适用于第一个字母

javascript - 如何设置文本框值以使用 javascript 上传文件名?

python日志记录模块没有向文件写入任何内容

java - 如何在带有验证注释的 bean 属性的测试用例中引发 ConstraintValidationException?

java - 当我的accept-count=100000时,为什么会出现SocketTimeoutException?

java - 独立 Java 单元测试 vs Tomcat Web 应用程序