0
        public static String priceReader(String clotheOrder) {
        
        String price = "";
        try {
            
            File file = new File("src\\application\\clotheprice.txt");
            Scanner scan = new Scanner(file);
            
            while (scan.hasNext()) {
                         
                String clotheCode = scan.next();
                String clothePrice = scan.next();
                String clotheStocks = scan.next();
                        
                if (clotheOrder == clotheCode) {
                            price = clothePrice;
                }
            }
            scan.close();
        }

            catch (FileNotFoundException e) {
            System.out.println("Error occured.");
            e.printStackTrace();
        }
        return price;
    }

Above is the java method that I'm trying to run. If this method is not functional, is there other way to read a file then return a string from the file? Thank you in advance.

  • Change your `if` statement with `if (clotheOrder.equals(clotheCode))` and you are good to go. – Marco Tizzano Jun 09 '21 at 15:30
  • @MarcoTizzano (Slightly) better is `Objects.equals(clotheOrder, clotheCode)`, as in the linked Q/A. – James_D Jun 09 '21 at 15:38
  • Despite what you see in the suggested answer, bear in mind that String does override equals from Object, and it properly compare two String objects. Honestly, I don't see the reason why you should instead use the one from Object :/ – Marco Tizzano Jun 09 '21 at 15:46
  • 2
    @MarcoTizzano Because `Objects.equals(clotheOrder, clotheCode)` handles the case where `clotheOrder` is `null`; your code would throw a `NullPointerException` in that case. (Whether or not `String` overrides `Object.equals` is irrelevant, and I don't know what you mean by "use the one from `Object`": `Objects.equals(a, b)` will invoke `a.equals(b)`, i.e. use the `String` implementation, if `a!=null`.) – James_D Jun 09 '21 at 15:50
  • Oh yeah the NullpointerException scenario, that makes sense. Good point. – Marco Tizzano Jun 09 '21 at 16:02

0 Answers0