糖果机Java

时间:2018-07-21 02:12:58

标签: java jgrasp

请帮助解决以下卡住的代码(我是Java新手) 作业说我需要用代码构建一台计算机糖果机。 这是作业的输出:

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!

或:

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

这是我的代码(我尚未完成):

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
   }
   }

我被困在verse4()中。我的意思是我做对了吗?如何在verse2()中使用“金钱”并在verse4()中使用它,或者该怎么办?请帮助我。

2 个答案:

答案 0 :(得分:1)

在我看来,verse2中的变量money在verse4的范围之外。 如果在方法内部定义变量,则该变量仅存在于该方法中。如果您这样写,它应该可以工作:

double money;

在您的课程的开括号下,然后更改

double money = console.nextDouble();

在第2节中:

money = console.nextDouble();

答案 1 :(得分:1)

您需要将cmd2变量声明为全局变量,以便可以在任何地方访问它。另外,由于您的方法都是静态的,因此它必须为cmd1。我确实启动了您的money方法,唯一需要考虑的是,如果用户没有足够的钱,会发生什么?这就是static被评论做作业的原因;)!另外,您必须知道verse4()else{...}之间的区别。它们在您的程序中至关重要。祝你好运。

>=