HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Menu List and interaction

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
andlistmenuinteraction

Problem

I am wondering if someone can review my code and tell me if there is a way to enhance it and make it more efficient.

import java.util.Scanner;

public class apples {
    public static void main (String[] args){
        Scanner input = new Scanner(System.in);

        int selection;

        for (int i=0; i4){
                System.out.println("You have made a wrong selection, please re-select");
            }
        }
    }
}

Solution

Whenever you find you have a situation where you are tring to match values to numbers, especically sequential numbers, the trick is to use an array. This makes the whole thing simpler, and centralizes the logic in one place, and the data in another.

Before we go there, though, some other things are:

  • Java class names should be Pascal case (upper-case word-starters), so it should be called Apple, and not apple.



  • There is no need to "pre-declare" variables. int selection; is unnecessary, just make the setting line: int selection = input.nextInt();



For example, your code could easily be:

import java.util.Scanner;

public class Apple {

    private static String[] DRINKS = { "Coffee", "Tea", "Juice", "Fizzy Drink" };

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        for (int i = 0; i = 0 && selection < DRINKS.length) {
                System.out.println("You have chosen " + DRINKS[selection]);
            } else {
                System.out.println("You have made a wrong selection, please re-select");
            }
        }
    }
}


Note how I have reused the DRINKS array when both printing the prompt, and selecting the Drink. Also note that you can add drinks just by changing the array.

Finally, I find that using printf(...) is convenient when formatting data.

Code Snippets

import java.util.Scanner;

public class Apple {

    private static String[] DRINKS = { "Coffee", "Tea", "Juice", "Fizzy Drink" };

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        for (int i = 0; i < 4; i++) {
            System.out.println("Please enter the selection you would like");

            for (int d = 0; d < DRINKS.length; d++) {
                System.out.printf("Enter %d for %s\n", d + 1, DRINKS[d]);
            }
            int selection = input.nextInt() - 1;
            if (selection >= 0 && selection < DRINKS.length) {
                System.out.println("You have chosen " + DRINKS[selection]);
            } else {
                System.out.println("You have made a wrong selection, please re-select");
            }
        }
    }
}

Context

StackExchange Code Review Q#93532, answer score: 6

Revisions (0)

No revisions yet.