控制台说扫描仪已关闭,我需要重新打开它。 Java错误

时间:2018-10-09 01:44:39

标签: 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();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

每次读取一行时,您就将fileReader循环中的Scanner分配给新的while。您要做的是将其分配在try块的顶部。这样,它将在块的末尾关闭。另外,如果这是您要执行的操作,请删除顶部的作业。此外,您可以让Java这样自动关闭它:

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

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

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

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