【问题标题】:Runtime error when passing string into boolean function to scan file for an identical string将字符串传递给布尔函数以扫描文件以查找相同字符串时出现运行时错误
【发布时间】:2017-11-09 02:22:37
【问题描述】:

我正在创建的程序的一部分需要检查是否已将相同的字符串(指示产品的 ID 代码)写入文本文件。这是为了阻止同一个 ID 被写入两次。

我正在使用一个布尔方法,它从 GUI 用户输入中传入一个字符串,然后将它与文件中每个已经存在的行进行比较。

方法如下。

public boolean hasIDAlreadyBeenUsed(String IDBeingTested) {
        boolean Decision = false;
        String ID = "Product ID: "+IDBeingTested;
        BufferedReader theBR;
        Scanner scanner;
        String scannedString;
        try {
            theBR = new BufferedReader(new FileReader("ProductData.txt"));
            scanner = new Scanner(new File("ProductData.txt"));

            while (scanner.hasNextLine()) {
                scannedString = scanner.nextLine();

                String character = scanner.findInLine(ID);


                if ((character) == (ID)) {
                    Decision = true;
                    System.out.println("they are a match: " + ID);

                } else {
                    Decision = false;
                }
            }
            theBR.close();
            theBR = null;
        } catch (IOException ioe) {
            Decision = false;
            System.out.println(ioe);
        }

        return Decision;
    } 

如果 boolean 返回 false,数据将被写入文件,如果返回 true,则会出现错误消息并且不写入数据。

以下是依赖于布尔输出的代码。

private void jAddProductToDatabseButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                           


        if (!product.hasIDAlreadyBeenUsed(jProductIDTextField.getText())) {
            try {
                BufferedWriter ProductFileWriter = new BufferedWriter(new FileWriter("ProductData.txt", true));

                ProductFileWriter.write("Product Name: " + jProductNameTextField.getText() + System.getProperty("line.separator"));
                ProductFileWriter.write("Product ID: " + jProductIDTextField.getText() + System.getProperty("line.separator"));
                ProductFileWriter.write("Product Weight: " + jProductWeightTextField.getText() + System.getProperty("line.separator"));
                ProductFileWriter.write("Product Selling Price (£): " + jProductSellingPriceTextField.getText() + System.getProperty("line.separator"));
                ProductFileWriter.write("Product Image File Name: " + jNameOfImageFileTextField.getText() + System.getProperty("line.separator"));
                ProductFileWriter.write("Product Manufacturer Address: " + jManufacturerAddressTextArea.getText() + System.getProperty("line.separator"));
                ProductFileWriter.write("Product Type: " + jProductTypeTextField.getText() + System.getProperty("line.separator"));
                ProductFileWriter.write("Product Unit Cost: " + jProductUnitCostTextField.getText() + System.getProperty("line.separator"));
                ProductFileWriter.write("Product Delivery Time: " + jProductDeliveryTimeTextField.getText() + System.getProperty("line.separator"));
                ProductFileWriter.write("Product Shelf Life: " + jProductShelfLifeTextField.getText() + System.getProperty("line.separator"));
                ProductFileWriter.write("Product Stock Level: " + jInitialStockLevelTextField.getText() + System.getProperty("line.separator"));
                ProductFileWriter.write("==============================" + System.getProperty("line.separator"));
                ProductFileWriter.flush();
                ProductFileWriter.close();
                ProductFileWriter = null;
            }
            catch (IOException ioe) {}

        } 
        else {

            JOptionPane.showMessageDialog(null, "Cannot input, ID HAS ALREADY BEEN USED", "Incorrect ID", JOptionPane.ERROR_MESSAGE);
        }
    }

但是 else 语句永远不会执行,即使相同的数字(例如 44)作为 ID 已多次输入。

我什至在里面用这个来表明字符串是一样的。并且产生了两次相同的字符串。

while (scanner.hasNextLine()) {
            scannedString = scanner.nextLine();

            String character = scanner.findInLine(ID);
            System.out.println(scannedString);
            System.out.println("Product ID: " + ID);

【问题讨论】:

标签: java boolean java.util.scanner bufferedreader filereader


【解决方案1】:

一旦找到匹配项,就必须中断循环,否则Decision 值将被覆盖到下一行。

public static boolean hasIDAlreadyBeenUsed(String IDBeingTested) {
    boolean Decision = false;
    String ID = "Product ID:" + IDBeingTested;

    Scanner scanner;
    String scannedString;
    try {

        scanner = new Scanner(new File("src/ProductData.txt"));

        while (scanner.hasNextLine()) {
            scannedString = scanner.nextLine();

            if (scannedString.equalsIgnoreCase(ID)) {

                Decision = true;
                System.out.println("they are a match: " + ID);
                break;

            }
        }

    } catch (IOException ioe) {
        Decision = false;
        System.out.println(ioe);
    }

    return Decision;
}

另外,我认为您在这里不需要 findInLine 方法。我希望这能解决你的问题。根据您的项目结构使用文件路径。

注意:: 如果我们在代码中遵循命名约定会很好。

【讨论】:

  • 这行得通,非常感谢。您能否澄清一下 src 仅表示文件路径的名称?或者这是不正确的?
  • src 是存放文件的文件夹。
【解决方案2】:

似乎错误来自此语句:

if ((character) == (ID)) {

这会比较 String 对象是否相同。

使用以下内容:

if (character.equals(ID)){

应该比较字符串的值。

【讨论】:

  • 我运行了这样的代码并收到以下错误,“AWT-EventQueue-0” java.lang.NullPointerException,你知道如何解决这个问题吗?
  • 我要比较的字符串是例如“产品 ID:4”和“产品 ID:4”.. 所以我认为我收到错误的原因是因为它试图导出一个数字字符串中的值。你知道我说的对吗?
【解决方案3】:

首先,您使用的是 Scanner 和 BufferedReader,在您的情况下,两者都可以使用,但都不是解决问题所必需的。 你可以试试 sn-p 之类的。

public static boolean hasIDAlreadyBeenUsed(String IDBeingTested) throws IOException {
        boolean Decision = false;
        String ID = "Product ID: "+IDBeingTested;
        BufferedReader theBR = null;
        String scannedString;
        try {
            theBR = new BufferedReader(new FileReader("ProductData.txt"));

            while ((scannedString=theBR.readLine())!=null) {
                if(!Decision)
                    Decision = scannedString.contains(ID);
                else
                    break;
            }
        } finally {
            theBR.close();
        }

        return Decision;
    }

我也想给一个提示,不要以大写字母开头变量名(通常类的第一个字母大写)。您可以参考一些在线教程,了解良好的编程实践。 干杯,

【讨论】:

    【解决方案4】:

    在 hasIDAlreadyBeenUsed() 方法中将您的比较代码更改为以下代码:

    String character = scanner.findInLine(ID);
    
    if ((character.trim().equals(ID)) { // by trimming I'm removing the line separator and then use equals to do a string comparision.
        Decision = true;
        System.out.println("they are a match: " + ID);
    } else {
        Decision = false;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-28
      • 1970-01-01
      • 2011-04-03
      • 2015-04-30
      • 1970-01-01
      相关资源
      最近更新 更多