Reputation: 25
So far I have written this code for a virtual vending machine:
public class VirtualVender {
public static void main(String[] args){
int MILK_CHOCOLATE = 01;
int DARK_CHOCOLATE = 02;
int LIGHT_CHOCOLATE = 03;
int COOKIE_CHOCOLATE = 04;
int SELECTION;
System.out.println("********************");
System.out.println("Vending Machine");
System.out.println("Enter Your Selection");
Scanner input = new Scanner(System.in);
SELECTION = input.nextInt();
System.out.println("********************");
}
}
So from my understanding the user input should now be stored in SELECTION, but how do I get SELECTION to bring up MILK_CHOCOLATE if I inputted 01? if you need a more indepth question just respond and I'll try and explain my question better.
Thanks for any help!
Upvotes: 1
Views: 1721
Reputation: 2363
Use cases man.
String output;
switch (selection) {
case 1: output = "milk chocolate";
break;
case 2: output = "dark chocolate";
break;
..
default: output = "Not a correct value."
}
I believe they resemble the vending machine problem or circuits in general the best.
Upvotes: 0
Reputation: 69399
Declare an enum that defines your flavours and associated integer values:
public enum Flavour {
MILK_CHOCOLATE(1),
DARK_CHOCOLATE(2),
LIGHT_CHOCOLATE(3),
COOKIE_CHOCOLATE(4);
private final int value;
private Flavour(int value) {
this.value = value;
}
public static Flavour fromValue(int value) {
for (Flavour f : values()) {
if (f.value == value) {
return f;
}
}
return null;
}
// Add a toString() method if you want to better control
// how the flavour names are printed
}
Then use your enum to validate the user input values:
System.out.println("********************");
System.out.println("Vending Machine");
System.out.println("Enter Your Selection");
// Use try-with-resources to close Scanner:
try (Scanner input = new Scanner(System.in)) {
int selection = input.nextInt();
Flavour flavour = Flavour.fromValue(selection);
if (flavour != null) {
System.out.println(flavour);
} else {
System.out.println("Bad selection!");
}
System.out.println("********************");
}
Upvotes: 1
Reputation: 84378
There are a lot of different ways to do it. Here's one:
if (SELECTION == MILK_CHOCOLATE) {
System.out.println("Please enjoy your milk chocolate.");
}
By the way, the convention is to use ALL_UPPERCASE
for constants, that is, values that will stay the same throughout the life of your program. So while MILK_CHOCOLATE
is a constant, the user's selection isn't. You should name that variable selection
instead. The Java compiler doesn't care, but the code will be easier for other programmers to read.
Upvotes: 1