首页 > 解决方案 > Candy Machine Java

问题描述

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.

标签: javajgrasp

解决方案


在我看来,verse2 中的变量money超出了 verse4 的范围。如果在方法中定义变量,它只存在于该方法中。如果你写它应该工作:

double money;

就在您班级的左括号下方,然后更改

double money = console.nextDouble();

在第 2 节中:

money = console.nextDouble();

推荐阅读