boolean acceptPcode=true;
boolean acceptQty=false;
int Qty=0;
List<Integer> purchasedProdQty=new ArrayList<>();
while(acceptPcode==true && acceptQty==false){
do{
try{
System.out.print("Enter Qty: ");
Qty=sc.nextInt();
acceptQty=true;
}catch(InputMismatchException ime){
System.out.println("Invalid quantity please enter a number!");
acceptQty=false;
}
if(acceptQty==true)
purchaseProdQty.add(Qty);
}while(acceptQty==false);
}
我的问题是,当我输入字母时,它会陷入无限循环,并且不会提示用户输入数量..
输入数量:无效数量,请输入数字!
输入数量:无效数量,请输入数字!
输入数量:无效数量,请输入数字!
您忘记阅读下一行的\n
(或\r\n
)字符。在您当前的代码中,扫描程序正在等待int
输入,而当前的下一个输入是此中断行字符。只需添加sc.nextLine()
代码即可使用换行符char:
Qty=sc.nextInt();
sc.nextLine();
acceptQty=true;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句