Issue
I am new to java and I am already stumped. I am trying to make a method that allows you to create a drink in console. I get stuck when using the if statements and setting the right size and drink type. When I run the code, everything works fine until when making it so when you type a certain number, it will set the size of the drink. If I type in 2 for the size option, which is assigned to Short, it will set Demi as the size even thought it should set Short when I type in 2, and Demi when I type 1. The method btw is in a subclass that extends a superclass and the method is to be called from the main class. If you need more info or if this is not enough code to tell what I'm doing specifically please let me know and I will try to give more info.
public void makeDrink(Scanner input) {
showOptions();
int choice = input.nextInt();
input.nextLine();
while (choice != 0) {
if (choice > 4 || choice < 0) {
System.out.println("You made a invalid choice, please reset");
}
/*
* Chose Size of the drink
*/
if (choice == 1) {
if(choice < 0 || choice > 6) {
System.out.println("You made a invalid choice, please try again");
}
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Choose the size");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("|1. Demi (3 oz)|2. Short (8 oz)|3. Tall (12 oz)|4. Grande (16 oz)|5. Venti (20 oz)|6. Trenta (30 oz)|");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
input.nextInt();
// first issue starts here
if (choice == 1) {
setSize("Demi");
}
if (choice == 2) {
setSize("Short");
}
// first issue ends here
}
/*
* Choose Drink
*/
if (choice == 2) {
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Choose the Drink");
System.out.println("~~~~~~~~~~~~~~~~~~");
System.out.println("|1. Coffee|2. Tea|");
System.out.println("~~~~~~~~~~~~~~~~~~");
String type = input.nextLine();
// second issue starts here
if (choice == 1) {
setType("Coffee");
}
if (choice == 2) {
setType("Tea");
}
// second issue ends here
showOptions();
choice = input.nextInt();
}
}
Solution
You need to remove this statement
if (choice == 1) { //this statement
if (choice < 0 || choice > 6) {
System.out.println("You made a invalid choice, please try again");
}
Or else when the choice
will be set to 1. The condition if (choice < 0 || choice > 6)
is always true.
Furthermore, the conditions:
if (choice == 1) {
is alwaystrue
if (choice == 2)
is alwaysfalse
.
You need to remove scanning the next line as well as it seems meaningless to me.
int choice = input.nextInt();
input.nextLine(); //remove this
Answered By - Zahid Khan
Answer Checked By - Pedro (JavaFixing Volunteer)