【问题标题】:How to avoid double printed statements with an if statement in a while loop如何避免在while循环中使用if语句重复打印语句
【发布时间】:2020-09-19 22:51:52
【问题描述】:

我是 * 的新手,想知道为什么当我在我的 while 循环中引入 if 语句@“如果完成,请键入“返回””时,我的语句会不断重复两次。其次,有人能告诉我为什么当我只向 ArrayList 添加一项时,ArrayList 在索引 0 处保留一个空字符串吗?谢谢!

代码如下:

包 com.codewithrichard;

导入 java.util.ArrayList; 导入 java.util.Scanner;

公共类主{

public static void main(String[] args) {
 Scanner input = new Scanner(System.in);

 //global variables
  boolean appIsStillOn = true;


 ArrayList <String> shoppingList = new ArrayList<>();

 System.out.println("Welcome to your mobile shopping list" + "\n" + "Your options are");
 System.out.println("1) add item to list");
 System.out.println("2) display list and amount of items in it");
 System.out.println("3) quit!");

 while (appIsStillOn) {
     System.out.println("Option (1-4): ");
     int option1 = input.nextInt();
     if (option1 == 1) {
         while (true) {
             System.out.println("item (if done, type \"back\"): ");
             String itemAdded = input.nextLine().toLowerCase();
             if (!itemAdded.equals("back")) {
                 shoppingList.add(itemAdded);
             } else {
                 break;
             }
         }
     }
     else if (option1 ==2){
         System.out.println(shoppingList);
         System.out.println("size of shopping list: "  + shoppingList.size());
     }
     else {
         System.out.println("Can't wait for you to come back!");
         appIsStillOn = false;
     }









 }










}

}

【问题讨论】:

  • 你试过调试吗?调试器中有什么不清楚的地方?
  • 第一次调用input.nextLine() 时,Scanner 会占用您在int 菜单选项中键入的行的其余部分。第一次调用将返回一个空字符串,该字符串将成为列表中的第一项。

标签: java if-statement arraylist while-loop


【解决方案1】:

在输入input.nextInt() 后,当您按下输入时,input.nextLine().toLowerCase() 会获取该行的数据,因为input.nextInt() 不会占用\n(换行符)。

input.nextInt()之后阅读换行符以跳过它

int option1 = input.nextInt();
input.nextLine();

【讨论】:

    【解决方案2】:

    Scanner#nextInt() 方法(以及许多其他 next...() 方法)不会消耗扫描仪缓冲区中的换行符ENTER 键被按下。 Scanner#nextLine() 方法会在 Scanner#nextInt() 方法之后使用它,因此给人的印象是提示输入被跳过了。

    还要考虑这个...

    如果用户不小心输入了字母字符而不是菜单选择数字,会发生什么?没错,您的应用程序会因为 InputMismatchException 而崩溃。

    您应该始终对用户输入进行某种形式的验证,如果验证失败,请允许用户进行正确的输入。在使用您的应用程序时,这显然会促进一个更无故障的环境。使用您当前的模型,这是一个示例:

    java.util.Scanner input = new java.util.Scanner(System.in);
    
    //global variables
    boolean appIsStillOn = true;
    ArrayList<String> shoppingList = new ArrayList<>();
    
    System.out.println("Welcome to your mobile shopping list.");
    
    while (appIsStillOn) {
        int option1 = 0;
        while (option1 < 1 || option1 > 3) {
            System.out.println();
            System.out.println("Your Shopping List options are:");
            System.out.println("  1) Add item to list.");
            System.out.println("  2) Display list and amount of items in it.");
            System.out.println("  3) Quit!");
            System.out.print("Choice (1-3): --> ");
            try{
                option1 = input.nextInt();
                if (option1 < 1 || option1 > 3) {
                    throw new java.util.InputMismatchException();
                }
                /* Consume the enter key hit (newline char) in case
                   a Scanner#nextLine() prompt is next so that it 
                   doesn't get consumed by that method.   */
                input.nextLine(); 
            }
            catch (java.util.InputMismatchException ex) {
                System.err.println("Invalid menu choice supplied! Try again...");
                /* Consume the enter key hit (newline char) in case
                   a Scanner#nextLine() prompt is next so that it 
                   doesn't get consumed by that method. It is also
                   required here in case an exception has bypassed 
                   the above 'input.nextLine()' call.*/
                input.nextLine(); // Consume the enter key hit (newline char)
            }
        }
    
        if (option1 == 1) {
            while (true) {
                System.out.println();
                System.out.println("Enter the item to add (when done, enter \"back\"): ");
                System.out.print("Item: --> ");
                String itemToAdd = input.nextLine();
                if (itemToAdd.trim().equals("")) {
                    System.err.println("Invalid Item String! You must supply something!");
                    continue;
                }
                else if (itemToAdd.equalsIgnoreCase("back")) {
                    break;
                }
                shoppingList.add(itemToAdd);
            }
        }
        else if (option1 == 2) {
            System.out.println();
            System.out.println(shoppingList);
            System.out.println("Number of Items in shopping list: " + shoppingList.size());
        }
        else {
            System.out.println();
            System.out.println("Bye-Bye - Can't wait for you to come back!");
            appIsStillOn = false;
        }
    }
    

    【讨论】: