有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java程序没有显示它应该显示的所有内容

我正在为一家书店编写一个清单程序,它由两个类和这些类中的多个方法组成

我遇到最大问题的方法是我的purchase()方法,它应该以交互方式处理购买,在购买后更新数组,并显示当天售出物品的总数和总收入

该方法应遵循以下10个步骤:

  1. 要求用户输入他们想要购买的图书的ISBN号

  2. 在数组中搜索包含该ISBN的对象

  3. 如果在数组中找不到ISBN,则显示一条消息,说明我们没有那本书

  4. 如果找到ISBN,但拷贝数为0,则显示一条消息,说明该书缺货

  5. 如果找到ISBN,并且拷贝数大于0,请询问用户希望购买多少拷贝

  6. 如果他们输入的数量大于数组中该书的份数,则显示一条消息说明这一点,并要求他们输入另一个数量

  7. 当他们为ISBN输入0时,扫描仪应关闭

  8. 一旦购买完成,我需要通过减去购买的特定书籍的拷贝数来更新数组

  9. 打印更新的数组

  10. 显示购买了多少本书以及从购买中赚了多少钱的计数

但是当我编写代码时,在程序提示我输入ISBN后,什么也没有发生,它只是让我不断地输入数字,而没有额外的输出

下面是我为这个方法编写的代码。我很确定这可能是我的循环的问题,因为我不太擅长循环。谁能看出我做错了什么

public static Book[] purchase(Book[] books) {
    int itemsSold = 0;
    double totalMade = 0;
    double price;
    int copies; 
    String isbn;
    Scanner input = new Scanner(System.in);
    int desiredCopies = 0;
    int index;
    double total = 0;

    System.out.println("Please enter the ISBN number of the book you would like to purchase: ");
    String desiredIsbn = input.next();

    for (index = 0; index < books.length; index++) {
        if (books[index].getISBN().equals(desiredIsbn) && books[index].getCopies() > 0) {
            System.out.println("How many copies of this book would you like to purchase?");

            if (!books[index].getISBN().equals(desiredIsbn))
                System.out.println("We do not have that book in our inventory.");
            if (books[index].getISBN().equals(desiredIsbn) && books[index].getCopies() == 0)
                System.out.println("That book is currently out of stock.");

            desiredCopies = input.nextInt();
        }

        if (desiredCopies > books[index].getCopies())
            System.out.println("We only have " + books[index].getCopies() + "in stock. Please select another quantity: ");

        desiredCopies = input.nextInt();
        books[index].setCopies(books[index].getCopies() - desiredCopies);

        if (input.next().equals(0)) 
            System.out.println("Thank you for your purchase, your order total is: $" + total);

        input.close();

        total = books[index].getPrice() * desiredCopies;
        itemsSold += desiredCopies;
        totalMade += total;

        System.out.print(books[index]);
        System.out.println("We sold " + itemsSold + " today.");
        System.out.println("We made $" + totalMade + "today.");
    }

    return books;
}

任何帮助都将不胜感激


共 (1) 个答案

  1. # 1 楼答案

    你不符合所有可能的条件

    你的if语句显然没有涵盖所有可能的条件排列

    您应该始终使用if/else if/else块来确保覆盖所有条件。除此之外,任何人都绝对不可能在几乎没有进展的情况下提供任何实际的解决方案

    ScannerStringTokenizer是JDK中除DateCalendar之外设计最差的两个类。他们给新人带来了无尽的麻烦,退伍军人也避免了他们