使用scanner JAVA时跳过do中的输入
我正在使用一个do-while循环,该循环基于用户的输入作为“Y”或“N”进行循环。如果用户选择按“Y”或1继续(为简单起见),则在第二次迭代时,它将跳过同一循环中的第一个输入使用scanner JAVA时跳过do中的输入,java,loops,java.util.scanner,do-while,Java,Loops,Java.util.scanner,Do While,我正在使用一个do-while循环,该循环基于用户的输入作为“Y”或“N”进行循环。如果用户选择按“Y”或1继续(为简单起见),则在第二次迭代时,它将跳过同一循环中的第一个输入 do{ System.out.println("Enter the location: "); cartItem.purchaseLocation = input.nextLine(); // This input is skipped on second iteration
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
因此,当用户按input 0重复该过程时,该行
cartItem.purchaseLocation=input.nextLine()
将跳过循环中的第一个输入。有什么建议吗?不要使用
input.nextLine()
使用input.next()
假设input
是一个Scanner
对象
如果不是,请澄清什么是输入。问题与
input.nextInt()不读取行,当您的输入为“1\n”时,它读取“1”,并将“\n”留给下一次读取,即
cartItem.purchaseLocation = input.nextLine();
您的解决方案无法解决问题,但会导致以后出现更多其他问题。