Java:收银机

时间:2013-11-23 18:24:44

标签: java

我正在为圣诞树构建一个收银机应用程序。我希望能够有多个交易,这样我就可以跟踪正在进行的树木数量。问题是我可以做一个交易,然后结束。我考虑过while循环,但也许我做错了因为它创建了一个无限循环。我该怎么办?

import java.util.Scanner;
public class PosTester 
{

    public static void main(String[] args) 
    {

        Scanner in = new Scanner(System.in);
        POS register = new POS();
        boolean done = false;

        while (!done)
        System.out.println("Please enter price of tree: ");
        double purchase = in.nextDouble();

        System.out.println("Is order complete? Type: Y/N");
        String choice = in.next();


        if (choice.equalsIgnoreCase("y"))

        {
            System.out.println("Your total is: " + purchase);
            System.out.println("<--------------------------->");
            System.out.println("Please enter payment amount: ");
            double payment = in.nextDouble();
            double change = payment - purchase;
            System.out.println("Your change is: $ " + change);
            int treeCount = 10; //lot contains 10 trees
            treeCount--; // remove tree from inventory

            if (treeCount == 5)
            {
                System.out.println("You're down to 5 Christmas Trees" );
            }
        }

        else if (choice.equalsIgnoreCase("n"))
        {
            System.out.println("Please add another item");
            System.out.println("Enter price of the next tree: ");
        }



    }

}

1 个答案:

答案 0 :(得分:2)

您的程序将无限期打印Please enter price of tree:

您意识到没有大括号的while仅适用于下一行?

while (!done)
    // do something
// do something else

以上只会在无限循环中执行do something。你真的想要围绕你想要循环的花括号:

while (!done) {
    // do something
    // set done to true at some point, or break from the loop
} 

一些提示:

  • 正确缩进代码有助于查看问题。大多数IDE都应该为您自动格式化代码,您会注意到System.out.printlnwhile缩进的方式与其他格式不同。

  • 如果您学习如何使用调试器,那么错误就会变得非常明显,因为在while之后您永远不会走出这条线。