Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用scanner JAVA时跳过do中的输入_Java_Loops_Java.util.scanner_Do While - Fatal编程技术网

使用scanner JAVA时跳过do中的输入

使用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-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
因此,当用户按input 0重复该过程时,该行

cartItem.purchaseLocation=input.nextLine()


将跳过循环中的第一个输入。有什么建议吗?

不要使用
input.nextLine()
使用
input.next()
假设
input
是一个
Scanner
对象

如果不是,请澄清什么是
输入。

问题与

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

cartItem.purchaseLocation = input.nextLine();

您的解决方案无法解决问题,但会导致以后出现更多其他问题。