[英]Method returning null value to database statement
我在名為ProductInsert的類中具有以下方法:
public float insertPrice() {
try {
System.out.println("Enter Product Price:");
setProductPrice(scanFloat.nextFloat());
}catch (InputMismatchException e){
System.out.println("Invalid Input!");
new ProductInsert().insertPrice();
}
return getProductPrice();
}
我還有一個名為ProductServices的類,具有以下Prepared語句數據庫執行:
PreparedStatement pstm = con.prepareStatement(insertQuery);
pstm.setFloat(2, insertPrice());
因此,當用戶在詢問價格時輸入字符串值“ asdfad”時,它將返回InputMismatch異常並再次調用insertPrice方法。 並且在第二次調用它並且用戶輸入浮點值“ 230.00”的情況下,pstm.setfloat將獲得空值,並在數據庫中插入“ 0.00”而不是“ 230.00”。 為什么???
產品價格的設置者和獲取者:
public float getProductPrice() {
return productPrice;
}
public void setProductPrice(float productPrice) {
this.productPrice = productPrice;
}
發生異常時,您將創建一個新實例new ProductInsert().insertPrice();
。
初始調用insertPrice()
所返回的值是此ProductPrice
實例(准備該語句的實例insertPrice()
的值,該值未設置(或設置為0.0)。
在catch
,直接調用insertPrice()
而不使用new ProductPrice()
,但是您肯定需要重置或使用錯誤的輸入,例如
//...
catch (InputMismatchException e){
System.out.println("Invalid Input!");
scanFloat.nextLine(); // will "eat" the wrong entry
insertPrice(); // try again
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.