首页 > 解决方案 > 控制台说扫描仪已关闭,我需要它重新打开。Java 错误

问题描述

到目前为止,这是我的所有代码,我不确定问题是什么。这是一个杂货收据程序,应该处理异常,用户可以更新文件中的产品列表。该程序将搜索文件并将收据吐出到我计算机中所有“购买”产品的收据文件中。

这是代码:

package groceries;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Project2_ReceiptPrinterV2 {

public static void main(String[] args) throws FileNotFoundException {

    // Declaring all of the variables and containers that the program needs

    File inFile = new File("C:\\Users\\camer\\Desktop\\CECS 274\\Pricelist.txt");
    Scanner fileReader = new Scanner(inFile);
    Scanner userInput = new Scanner(System.in);
    String input;

    String itemRegex = "([\\w |\\W]+[s|\\w])\\s+(\\w[\\w |\\W]+\\S)\\s+([\\w |\\W]+\\s[\\w]+\\w)"; 
    String regexFull = "([\\w |\\W]+[s|\\w])\\s+(\\w[\\w |\\W]+\\S)\\s+([\\w |\\W]+\\s[\\w]+\\w)\\s+([\\w |\\W]+)";

    Pattern fullItemPattern = Pattern.compile(regexFull, Pattern.CASE_INSENSITIVE); 
    Pattern noPricePattern = Pattern.compile(itemRegex, Pattern.CASE_INSENSITIVE);

    Matcher fileMatcher; 
    Matcher userMatcher;

    System.out.println("Enter the output filename: "); // Create the file name 
    String outFileName = userInput.nextLine();
    PrintWriter outFile = new PrintWriter("C:\\Users\\camer\\Desktop\\Receipts\\" + outFileName +".txt");
    StringBuilder returnedString = new StringBuilder();
    final int maxLen = 60;

    ArrayList<Item> products = new ArrayList<>();
    ArrayList<String> buffer = new ArrayList<>();
    NumberFormat formatter = NumberFormat.getCurrencyInstance();

    String product;
    int holder;
    boolean inList = false;
    double total = 0.0;
    int numberOfItems;
    String quantifier;
    String itemPrice;
    boolean runProgram = true;
    String ProductEntry = "";
    String ProductEntryName = "";
    String ProductQuality = "";
    double ProductEntryPrice = 0;

    // Starting the user input loop


    while (runProgram) {
        System.out.println("Enter a product to add to your cart:\nEnter 'done' when finished.");
        input = userInput.nextLine().trim();
        if (input.equalsIgnoreCase("done")) {
            break;
        }
        else {
            userMatcher = noPricePattern.matcher(input);
        }
        try {
            if (userMatcher.find()) {
                while (fileReader.hasNextLine()) {

                    fileReader = new Scanner(inFile);

                    fileMatcher = fullItemPattern.matcher(fileReader.nextLine());

                    if (fileMatcher.find()) {
                        if (fileMatcher.group(1).trim().equals(userMatcher.group(1)) && fileMatcher.group(2).trim().equals(userMatcher.group(2)) && fileMatcher.group(3).trim().equals(userMatcher.group(3))){
                            product = fileMatcher.group(1) + " " + fileMatcher.group(2).trim();
                            Item itemHolder = new Item(product, Double.parseDouble(fileMatcher.group(4)), fileMatcher.group(3).trim());


                            if (products.contains(itemHolder)) {
                                // Adding the first product
                                products.get(products.indexOf(itemHolder)).incQuantity();
                            }
                            else {
                                // Adding multiple products after that
                                products.add(itemHolder);
                            }
                            // User feedback that the item was added
                            inList = true;
                            System.out.println("Product added!");
                        }
                    }
                }
            }
            if (!inList) {
                // If there is no such item in the file
                throw new IOException();
            }
            else {
                inList = false;
            }
            // Resetting the fileReader for each new item
            fileReader.close();
            fileReader = new Scanner(inFile);

        }
        catch(IOException exception) {
            System.out.println("Error! Selected product is not listed in file!");
            System.out.println("Would you like to correct your entry?");
            String UserResponse = userInput.nextLine().trim();
            if(UserResponse.equals("yes")) {
            }
            if (UserResponse.equals("no")) {
                System.out.println("Would you like to add your selected entry in to the file");
                String UserResponse2 = userInput.nextLine().trim();
                    if(UserResponse2.equals("yes")) {}
                        try {
                            File PriceList = new File("C:\\Users\\camer\\Desktop\\CECS 274\\Pricelist.txt");
                            FileWriter NewEntry = new FileWriter(PriceList, true);
                            BufferedWriter added = new BufferedWriter(NewEntry);
                            added.newLine();
                            System.out.println("Adding selected product into file now ...");
                            System.out.println("Enter Product name: ");
                            ProductEntry = userInput.nextLine().trim();
                            ProductEntryName = ProductEntry.split(" ")[0];
                            ProductQuality = ProductEntry.split(" ")[1];
                            ProductEntryName = ProductEntryName + " " + ProductQuality;
                            System.out.println("Enter the Size/Weight of the product");
                            String ProductEntrySize = userInput.nextLine().trim();
                            System.out.println("Enter the price of the product");
                            ProductEntryPrice = userInput.nextDouble();
                            String NewProduct = ProductEntryName + " " +  ProductEntrySize + " " + ProductEntryPrice;
                            added.write(NewProduct);
                            System.out.println("Product added!\n");
                            added.close();



                     }
                     catch (IOException error) {
                         error.printStackTrace();
                     }
                     if(UserResponse2.equals("no")) {
                         break;
                     }
                 }
                 }

        finally {

                // Outputting to the file
                for (int i = 0; i <= 60; i ++) {
                    outFile.print("_");
                }
                outFile.println();
                outFile.println("Java Market");
                outFile.println("242 W Santa Cruz St");
                outFile.println("San Pedro, CA");
                outFile.println("90731");
                outFile.println();
                outFile.println("Product                                              Subtotal");

                // Looping through products and processing multiples, formatting strings, and outputting to the file
                for (Item a : products) {
                    buffer.add(a.toString());
                    total += a.getTotalPrice();
                }

                Collections.sort(buffer);
                for (String b : buffer) {
                    outFile.println(b);
                }
                //outFile.println();

                for (int i = 0; i <= 60; i ++) {
                    outFile.print("_");
                }
                // Skipping lines and printing the formatted total
                outFile.println();
                outFile.println();
                outFile.println();
                outFile.printf("Your total is: $%.2f", total);
                outFile.println();
                for (int i = 0; i <= 60; i ++) {
                    outFile.print("_");
                }
                // Closing the out file and file reader after everything is done
                outFile.close();
                fileReader.close();
            }
        }
    }
}

标签: java

解决方案


每次阅读一行时,您都在循环中分配fileReader一个新的。您要做的是将其分配在块的顶部。这样,它将在块的末尾关闭。此外,如果这是您想要做的,请删除顶部的作业。此外,您可以让 Java 像这样自动关闭它:Scannerwhiletry

try (Scanner fileReader = new Scanner(inFile)) {
    ...

另一个注意事项是,使用 aBufferedReader而不是 a通常更快(也许更容易) Scanner。我相信您的情况的唯一区别是使用readLine()而不是nextLine(). 您还可以检查null一行而不是fileReader.hasNextLine(). 看起来像这样:

try (BufferedReader fileReader = new BufferedReader(new FileReader(inFile))) {
    ...

请注意,如果您使用它,则不应fileReader在其他任何地方声明或分配,或关闭它,因为它在用作try块资源时会自动关闭。


推荐阅读