lundi 20 septembre 2021

Trying to run Else statement inside For Loop

I have a small issue with my application that I spotted when testing it. I need to have a line of code that will run to inform the user they have entered an invalid product code.

The issuing I'm having is that I can't simply put it in an Else statement inside the For Loop because it will run every time a product code doesn't match until it finds a code that does, thus making it run multiple times.

Any help would be greatly appreciated, thank you :)

static void searchProduct() {
     
      System.out.print("Please enter product code to search: ");
      String searchTerm = in.nextLine().toUpperCase();
      
          for (int i = 0; i < report.size(); i++) {

              if (report.get(i).code.equals(searchTerm)) { 

                  System.out.println("****************************************************************************"
                                   + "\nPRODUCT SEARCH RESULTS"
                                   + "\n****************************************************************************");

                  System.out.println("PRODUCT CODE >>         " + report.get(i).code); 

                  System.out.println("PRODUCT NAME >>         " + report.get(i).name);

                  System.out.println("PRODUCT CATERGORY >>    " + report.get(i).category);

                  System.out.println("PRODUCT WARRANTY >>     " + report.get(i).warranty);

                  System.out.println("PRODUCT PRICE >>        " + report.get(i).price);

                  System.out.println("PRODUCT LEVEL >>        " + report.get(i).stock);

                  System.out.println("PRODUCT SUPPLIER >>     " + report.get(i).supplier);

                  System.out.println("****************************************************************************");
              }
              
              else {
                  // System.out.println("The product cannot be located. Invalid Product");
              }    
          } 
      
      System.out.println("Enter (1) to launch menu or any other key to exit");
      String opt2 = in.nextLine();

          if (opt2.equals("1")) {

              mainMenu.Menu();

          }

          else { System.exit(0); }
  }

Aucun commentaire:

Enregistrer un commentaire