【问题标题】:Trouble with getting an index of an array in java [duplicate]在java中获取数组索引的问题[重复]
【发布时间】:2016-09-04 22:58:23
【问题描述】:

我使用 BufferedReader 从 txt 文件中读取信息。我知道文件正在读取,但我无法选择第一个索引(bookID 号)来通过我的 if 语句。 我希望字符串的第一行与 bookID 匹配,然后完成 if 语句而不跳到 book is not found 语句。下面的代码。

 String bookID =  jTextField7.getText();
    String quantity = jTextField8.getText();


    jLabel9.setText("Item #" + Integer.toString(currItem) + "info");

    jButton8.setEnabled(false);
    jButton9.setEnabled(true);

    BufferedReader br = null;
    String sCurrentLine;

    try {

        //String sCurrentLine;
        br = new BufferedReader(new FileReader("inventory.txt"));


        while ((sCurrentLine = br.readLine()) != null) {

          String[] split = sCurrentLine.split(",");
          System.out.println(sCurrentLine);

                if (split[0] == bookID) {
                    int discount = calculateDiscount(Integer.parseInt(quantity));
                    double itemSubTotal = (Integer.parseInt(quantity)*new BigDecimal(split[2]).doubleValue()*(discount/100));
                    subTotal += itemSubTotal; 
                    String info = split[0] + " " +  split[1] + " " + split[2] + " " + quantity + " " + Integer.toString(discount) + " " + (Integer.parseInt(quantity)*new BigDecimal(split[2]).doubleValue()*(discount/100));
                    books.add(info);
                    jTextField9.setText(info);
                        return;
                }
        }
    }
    catch (IOException e ){
        e.printStackTrace();
    }
    finally {
        try {
            if (br != null)br.close();
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    JOptionPane.showMessageDialog(null, "Book ID " + bookID + " not in File"); 

}                                       

我将不胜感激。谢谢。

【问题讨论】:

  • inventory.txt的内容是什么?
  • 11111,“最高机密 21 - Janet Evanovich”,8.99 22222,“W 是浪费 - Sue Grafton”,9.95 33333,“Gray Mountain - John Grisham”,14.95 44444,“复兴 - Stephen King", 12.95 55555, "Everyday Italian - Giada de Laurentiis", 18.99 66666, "拒绝 - Felix Francis", 7.99 77777, "Dust - Patricia Cornwell", 12.99 88888, "Terminal City - Linda Fairstein", 10.95 99999, “Rogue Lawyer - John Grisham”,15.95 11112,“The Guilty - David Baldacci”,14.95 @shmosel,这是 bookID、book、author、price

标签: java arrays bufferedreader


【解决方案1】:

要比较字符串,您需要使用等号:

split[0].equals(bookId)

【讨论】:

  • 我进行了更改,但仍然收到相同的结果。
猜你喜欢
  • 2020-04-08
  • 2013-10-05
  • 1970-01-01
  • 1970-01-01
  • 2012-11-27
  • 1970-01-01
  • 2013-07-18
  • 1970-01-01
  • 2022-08-17
相关资源
最近更新 更多