Please help solve the following code I got stuck (i'm new to java) the homework said I need to build a computer candy machine in code. here is the output of the homework:
Welcome to Shoreline's Computer Candy Machine!
(All candy provided is virtual.)
How much money do you have? > $1.00
$1.00, that's all?
Well, let me tell you what we got here.
A $0.65 Twix
B $0.50 Chips
C $0.75 Nutter Butter
D $0.65 Peanut Butter Cup
E $0.55 Juicy Fruit Gum
So, What do you want? > C
Thanks for purchasing candy through us.
Please take your candy and your $0.25 change!
or:
Welcome to Shoreline's Computer Candy Machine!
(All candy provided is virtual.)
How much money do you have? > .50
$0.50, that's all?
Well, let me tell you what we got here.
A $0.65 Twix
B $0.50 Chips
C $0.75 Nutter Butter
D $0.65 Peanut Butter Cup
E $0.55 Juicy Fruit Gum
So, What do you want? > D
You are short $0.15, you are unable to purchase your snack
here is my code(i haven't finished it):
import java.util.Scanner;
public class CandyMachine {
public static void main(String[] args) {
verse1();
System.out.println();
verse2();
System.out.println();
verse3();
System.out.println();
verse4();
}
public static void verse1() {
System.out.println("Welcome to Shoreline's Computer Candy Machine!");
System.out.println("(All candy provided is virtual.)");
}
public static void verse2() {
Scanner console = new Scanner(System.in);
System.out.print("How much money do you have? >"); //prompts for a whole number
double money = console.nextDouble();
System.out.printf("%.2f, that's all?", money);
}
public static void verse3() {
System.out.println("Well, let me tell you what we got here.");
System.out.println("A $0.65 Twix");
System.out.println("B $0.50 Chips");
System.out.println("C $0.75 Nutter Butter");
System.out.println("D $0.65 Peanut Butter Cup");
System.out.println("E $0.55 Juicy Fruit Gum");
}
public static void verse4() {
Scanner input = new Scanner(System.in);
System.out.print("So, What do you want? >"); //prompts for a whole number
String a = input.next();
if (a.equals("A"))
if (money > 0.65)
System.out.println("Thanks for purchasing candy through us.");
else
}
}
I got stuck in verse4()
. I mean am I doing it right? How can I take "money" in verse2()
and use it in verse4()
or what should I do? Please help me.
It looks to me like the variable money
in verse2 is outside the scope of verse4.
If you define a variable inside a method, it only exists in that method. It should work if you write:
double money;
right under the opening bracket of your class, then change
double money = console.nextDouble();
in verse2 to:
money = console.nextDouble();