0

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!

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

As i is used for printing with 1 being added to it, I decided to do it this way for the OP to understand. Probably for myself, I would index from 0 though.
Ok, fair enough.
2

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");
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.