代码之家  ›  专栏  ›  技术社区  ›  NoviceProgrammer741

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

  •  1
  • NoviceProgrammer741  · 技术社区  · 7 年前

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

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

    每行应该有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();
    
    
    
        }
    
    }
    

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

    学习Java-William Lane-12.00-Wiley-0811234561

    William Stalling-25.00-普伦蒂斯大厅-1304086641

    OOP编程-Graham Winter-32.50-O'Reilly-0471974555

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

    用Perl-19.99-Wiley-0476887021编程

    多媒体通信-Fred Halsall-53.99-Addison Wesley-020398184

    网络指南-塔马拉院长-34.50-课程技术-1439055661

    MySQL指南-保罗·巴里-汤姆森-1418834351

    CCDA考试指南-安东尼·布鲁诺-49.95-思科出版社-0735700745

    Perl和CGI-Elizabeth Castro-99.50--0201735687

    802.11安全-Jon Edney-68.99-Addison Wesley-0321136209

    网页设计-Hoel Sklar-9.99-课程技术-

    大规模局域网-Kevin Dooley-39.00-O'Reilly-0596001509

    HTML和JavaScript:David Gast-12.00-Wiley 0471383661

    数据库和网络-Simon Burns-12Q-Perasons-0559000412

    无线黑客-Rob Weeks-29.50-O'Reilly-0596101442

    犯罪痕迹-尼尔·巴雷特-5.99-科基图书-055X215001

    2 回复  |  直到 7 年前
        1
  •  1
  •   Tushar Banne    7 年前

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

    总计

    书籍总数:6本
    一本书的总成本:177.93美元
    一本书的最低成本:12.00美元
    一本书的最高成本: 53.99美元一本书的平均成本:29.66美元有效书籍总数:6本 无效书籍总数:0

    这是预期的吗?

        2
  •  0
  •   Mohammed Housseyn Taleb    7 年前
      if(splitArray.length == 5)
        {// you have forgotten this
    
                splitArray[0] = splitArray[0].trim();
            .
            .
            .
        count++; }
            } // you should add this
        else {
            invalidcount++; 
        } 
    

    还有一个问题,我确信你漏掉了一点 如果在一本书中发现了无效的行,例如一个缺少的标题,你不应该将其视为无效的书?这取决于你的作业。你应该给它一个虽然

    但如果我的GES是对的

    您必须按以下方式编辑:

    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) throws IOException {
    
            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;
            int globalcount=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");
                Fileobject.createNewFile();
                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()) {
                    globalcount ++;
                    line = fileReader.nextLine();
    
                    String[] splitArray = line.split("-");
    
                    boolean validline ;
                    validline = splitArray.length == 5;
                    if (validline) {
    
                        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 = false;
                            System.out.println("Title is missing\n");
                        }
                        if (splitArray[1].isEmpty()) {
                            validline = false;
                            System.out.println("Author is missing\n" + line);
                        }
                        if (splitArray[2].isEmpty()) {
                            validline = false;
                            System.out.println("Price is missing\n" + line);
                        } else {
                            try {
                                Double.parseDouble(splitArray[2]);
    
                            } catch (Exception e) {
                                System.out.println("bad price format :\n" + line);
                                validline = false;
                            }
                        }
    
                        if (splitArray[3].isEmpty()) {
                            validline = false;
                            System.out.println("Publisher is missing\n" + line);
                        }
                        if (splitArray[4].isEmpty()) {
                            validline = false;
                            System.out.println("ISBN is missing\n" + line);
                        }
    
                        if (validline) {
                            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++;
                        }
                    } 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: " + globalcount);
            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();
    
        }
    
    }