【问题标题】:skipping input in do-while using scanner JAVA [duplicate]在使用扫描仪JAVA时跳过输入[重复]
【发布时间】:2013-12-04 01:36:35
【问题描述】:

我正在使用一个 do-while 循环,该循环根据用户的输入作为“Y”或“N”进行循环。如果用户选择按“Y”或 1(为简单起见)继续,则在第二次迭代时,它将跳过同一循环中的第一个输入。

do{
       System.out.println("Enter the location: ");
       cartItem.purchaseLocation = input.nextLine();  // This input is skipped on second iteration

       System.out.println("Enter the product description: ");
       cartItem.productDescription = input.nextLine();

       System.out.println("Enter the price of the item: ");
       cartItem.productPrice = input.nextDouble();

       System.out.println("Enter the quantity: ");
       cartItem.quantity = input.nextInt();


       cartList.add(cartItem);

       System.out.println("Do you want to add more items ? y = 1 / n = 0: ");
       exitVar = input.nextInt();

   }while(exitVar!=0);            // Repeat till no more items need to be added in the cart

所以当用户按下输入 0 重复该过程时,行

cartItem.purchaseLocation = input.nextLine();

将跳过循环中的第一个输入。有什么建议这里可能有什么问题吗?

【问题讨论】:

    标签: java loops java.util.scanner do-while


    【解决方案1】:

    Skipping nextLine() after use nextInt()相同的问题

    input.nextInt() 不读取一行,当您输入“1\n”时,它会读取“1”并将“\n”留给下一次读取,即

    cartItem.purchaseLocation = input.nextLine();
    

    【讨论】:

      【解决方案2】:

      假设inputScanner 对象,而不是使用input.nextLine() 使用input.next()

      如果不是,请说明input 是什么。

      【讨论】:

      • 您的解决方案无法解决问题,但会导致更多其他问题。
      猜你喜欢
      • 1970-01-01
      • 2015-12-13
      • 2013-01-31
      • 2018-05-30
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 2020-12-03
      相关资源
      最近更新 更多