gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:58:31 26 4
gpt4 key购买 nike

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

这是代码:

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

最佳答案

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

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

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

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

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

关于java - 控制台说扫描仪已关闭,我需要将其重新打开。 Java错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52712213/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com