如何阻止我的代码重复打印菜单?

How can I stop my code from duplicating menu printing?

我正在为学校做作业,一切都按预期工作,但我的菜单没有按我想要的方式工作。这是我做的一个测试 class,它与我的 Main class 基本相同,但很多情况都是空的,所以我可以试着弄清楚它到底发生了什么。

import java.util.Scanner;
public class Test {
    
    public static void main(String[] args) {
        
        Scanner input = new Scanner(System.in);
        Order array[] = new Order[100];
        boolean on = true;
        
        do {
            System.out.println("*** Choice Action "
                    + "\nA) Add an Order "
                    + "\nB) Compute Total Costs "
                    + "\nC) Search for an Order "
                    + "\nD) List Orders "
                    + "\nE) Quit");
            System.out.println("What action would you like to perform?");
            
            String userInput = input.nextLine().toLowerCase();
            
            switch(userInput) {
            case "add an order": 
                continue;
            case "compute total costs":
                continue;
            case "search for an order":
                System.out.println("Please enter a product name to search: ");
                String search = input.next();
                boolean found = false;
                for (int i = 0; i < 100; i++) {
                    if (array[i] != null) {
                        if (array[i].productName.equals(search)) {
                            System.out.println("Product found!");
                            break;
                        }
                    }
                }
                if (!found) {
                    System.out.println("Product not found.");
                }
                break;
            case "list orders":
                continue;
            case "quit":
                on = false;
                break;
            default:
                System.out.println("Unknown action");   
            }
            
        } while (on);
        
        input.close();
    }
}

因此,当我 运行 代码时,我最终会再次显示菜单两次,第一次只是提供默认大小写,然后第二次接受输入。我尝试将扫描器对象的创建和关闭移动到 do 循环中,但在进入第二个循环后它最终失败了,因为扫描器找不到下一行。

*** Choice Action 
A) Add an Order 
B) Compute Total Costs 
C) Search for an Order 
D) List Orders 
E) Quit
What action would you like to perform?
search for an order
Please enter a product name to search: 
test search
Product not found.
*** Choice Action 
A) Add an Order 
B) Compute Total Costs 
C) Search for an Order 
D) List Orders 
E) Quit
What action would you like to perform?
Unknown action
*** Choice Action 
A) Add an Order 
B) Compute Total Costs 
C) Search for an Order 
D) List Orders 
E) Quit
What action would you like to perform?

查看第 String search = input.next(); 行。 我觉得应该是String search = input.nextLine();.

从你的输出中应该很明显 Unknown action。因此,读取错误(空)行,它被解释为 Unknown action.