Home > database >  Search from ArrayList and output objects to be a new menu
Search from ArrayList and output objects to be a new menu

Time:08-17

My code to search from ArrayList:

public void searchFromList() {
        String color;
        System.out.print("Input the color: ");
        Scanner scan = new Scanner(System.in);
        color = scan.nextLine();
        boolean test = false;
        for (Fruit fruit: fruits) {
            if (fruit.getcolor().equals(color)) {
                System.out.println(fruit);
                test = true;
            }
        }
        if (!test){
            System.out.println();
            System.out.println("Sorry there is no "   color   " fruit in list");
        }
    }

If input is "green", output will be:

01 Pear
03 Watermelon

How do I make the output be a menu like:

[1] 01 Pear
[2] 03 Watermelon
[3] Back to Menu

Thank you! This is not an assignment, please feel free to give advice!

CodePudding user response:

Rather than a for-each loop, use an iterated loop and the use iterator as part of the output.

for (int i = 1; i <= fruits.length; i  ) {
    Fruit fruit = fruits[i - 1];
    // including your stuff
    System.out.printf ("[%d] %s%n", i, fruit);
    
}

not tested or even compiled

CodePudding user response:

You can add a counter to check the number of fruits found, and then use this counter to construct the menu form.

Your code would be like this:

public void searchFromList() {
        String color;
        System.out.print("Input the color: ");
        Scanner scan = new Scanner(System.in);
        color = scan.nextLine();
        boolean test = false;
        // Add Menu Item Counter Here
        int itemCount = 0;
        for (Fruit fruit: fruits) {
            if (fruit.getcolor().equals(color)) {
                System.out.println("["     itemCount   "]"   fruit);
                test = true;
            }
        }
        if (!test){
            System.out.println();
            System.out.println("Sorry there is no "   color   " fruit in list");
        }
        // Print Menu Item Here
        System.out.println("["     itemCount   "] Back To Menu");
    }
  • Related