简体   繁体   中英

Java for loop running both true and false conditions

I refactored a working project to practice creating callable methods when I broke the app. This app includes a simple String array with a method that matches user input with the array and prints the element name and index.

If I don't include a break at the end of the if else statements the app can match valid input but runs both if and else statements. It actually prints the if statement in the order of the index and prints the else output the number of times as the length of the array. In the attached pic, the input was index 0. if statement output In the pic index 0 was matched and printed with the number of else outputs as in the array. It seems the else statement is reading the array length.

If I add the break, the app only recognizes index 0 and will run the if statement as expected, but also runs the else statement. But only prints out if else output once. I hope this is clear. Trainers have simply said it is impossible to for a for loop to print of which I understand, yet I'm having a different experience.

Here is the code:

import java.util.Scanner;

public class Main {
  static Scanner scan = new Scanner(System.in);

  public static void main(String[] args) {

    System.out.println("What are you looking for? ");
    //String product = scan.nextLine();
    String[] aisles = {"apples", "bananas", "candy", "chocolate", "coffee", "tea"};
    searchProduct(aisles);
  }

  public static void searchProduct(String[] aisles) {
    String product = scan.nextLine();
    for (int i = 0; i < aisles.length; i++) {
      if (product.equals(aisles[i])) {
        System.out.println("We have " + aisles[i] + " in aisle " + i);

      } else {
        System.out.println("Sorry we do not have that product");

      }
    }
  }
}

I expect to match valid user input and run the if statement or run the else statement.

Here is a suggestion.

  • Change your method to return an int ( aisle if the product exists or -1 if not).
  • Don't do any I/O in the method. Just pass the target of the search as an argument.
String[] aisles = {
        "apples","bananas","candy","chocolate","coffee","tea"
};
System.out.println("What are you looking for? ");
String product = scan.nextLine();

int aisle = searchProduct(product, aisles);
if (aisle >= 0) {
    System.out.println("We have " + product + " in aisle " + aisle);
} else {
    System.out.println("Sorry we do not have that product");
}
    

public static int searchProduct(String product, String[] aisles) {
    for (int aisle = 0; aisle < aisles.length; aisle++) {
        if (product.equals(aisles[aisle])) {
            return aisle;
        }
    }
    return -1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM