首页 > 解决方案 > 如何根据文本文件中的特定关键字解析文本文件

问题描述

我目前有一个文本文件,我想将其解析为类。但是,我无法弄清楚为什么它没有正确执行。任何建议或帮助将不胜感激。

代码:

`

            case "1":
                try{
                    //Create file
                    File inputFile = new File("C:/Users/Olivia/Desktop/CIS331/products.txt");
                    Scanner scanner = new Scanner(inputFile);
                    //read data from file
                    while (scanner.hasNext()){
                        String type = scanner.nextLine();
                        //System.out.println(type);
                        if (type.equals( "PRODUCT")){
                            String pName= scanner.nextLine();
                            String pDescription = scanner.nextLine();
                            int pQuantity = Integer.parseInt(scanner.nextLine());
                            double pPrice = Double.parseDouble(scanner.nextLine());
                            boolean add = Product.addProduct(pName, pDescription, pQuantity, pPrice);
                            break;
                        }
                        else if (type.equals("AUTOMOBILE")){
                            String pName= scanner.nextLine();
                            String pDescription = scanner.nextLine();
                            int pQuantity = Integer.parseInt(scanner.nextLine());
                            double pPrice = Double.parseDouble(scanner.nextLine());
                            int y = Integer.parseInt(scanner.nextLine());
                            String mm = scanner.nextLine();
                            boolean add = Automobile.addAutomobile(pName, pDescription, pQuantity, pPrice, y, mm);
                            break;
                        }
                        else if (type.equals("VIDEO")){
                            String pName= scanner.nextLine();
                            String pDescription = scanner.nextLine();
                            int pQuantity = Integer.parseInt(scanner.nextLine());
                            double pPrice = Double.parseDouble(scanner.nextLine());
                            String genre = scanner.nextLine();
                            String rate = scanner.nextLine();
                            int time = Integer.parseInt(scanner.nextLine());
                            String star = scan.nextLine();
                            boolean add= Video.addVideo(pName, pDescription, pQuantity, pPrice, type, rate, time, star);
                           break;
                        }}
                        System.out.println("File read successfully");                         
                }
                catch (FileNotFoundException e) {
                    System.out.println("Error reading" + e.toString());
                }
                break;

`

.txt 文件: 这是输入文件

标签: java

解决方案


推荐阅读