我在做一個學校項目。我希望用戶訂購產品,顯示訂單審覈,然後選擇是否要確認或拒絕訂單。但是,該程序停留在無限循環中。我知道這與變量valid
有關,但我不知道爲什麼因爲我爲了停止循環而宣佈它爲true
。如果我刪除了確認部分,那麼一切正常。我的邏輯正確嗎?
public void selectOrder(Vector <Stock> temp){
sc.useDelimiter("\n");
String conf = "[YyNn]";
String exit = "[e][x][i][t]";
valid = false;
out = false;
confirm = false;
do{
System.out.println("Enter Product ID to Order: (Type exit to Quit)");
pid = sc.next();
if(pid.matches(chkpid)){
out = false;
for(int i = 0; i < temp.size(); i ++){
s = temp.elementAt(i);
if(pid.equals(s.getPid())){
l = i;
found = true;
break;
}else
found = false;
}
v = true;
do{
try{
System.out.println ("Please Enter Quantity to Order: ");
q = sc.nextInt();
v = false;
}catch(InputMismatchException ime){
sc.next();
System.out.println ("Invalid Input. Try Again.");
}
}while(v);
if(found == true){
oldQty = temp.elementAt(l).getQuantity();
originalQty = Integer.parseInt(oldQty);
afterQty = originalQty - q;
cst = temp.elementAt(l).getCost();
cost = Integer.parseInt(cst);
System.out.println();
System.out.println ("-------------Order Review-------------");
System.out.println ("Product Name: " + temp.elementAt(l).getName());
System.out.println ("Quantity: " + q);
System.out.println ("Price Preview(excluding tax): €" + (cost * q));
System.out.println ("--------------------------------------");
System.out.println();
do{
System.out.println ("Confirm Order? (Y/N)");
con = sc.next();
}while(!(con.matches(conf)));
if(con.equals("y") && con.equals("Y")){
if((originalQty > 0) && (afterQty >= 0)){
String newQty = Integer.toString(afterQty);
temp.elementAt(l).setQuantity(newQty);
System.out.println ("Order Successfull.");
valid = true;
}else if(originalQty <= 0){
System.out.println ("Product is Currently out of Stock!");
valid = false;
}else if(afterQty < 0){
System.out.println ("Quantity exceeds Stock Available!");
valid = false;
}
}
}else{
System.out.println ("Product ID Not Found!");
valid = false;
}
}else if (!(pid.matches(chkpid)) && !(pid.matches(exit))){
System.out.println ("Invalid Product ID Format.");
valid = false;
}
if(pid.matches(exit))
out = true;
}while((valid != true) && !(pid.matches(exit)));
System.out.println();
}
您正在調試嗎?代碼在哪裏? – boctulus
@Boctulus不,我仍然是一個初學者在java中,不太清楚如何調試。 –
你可以粘貼你的輸出打印語句嗎? – SMA