[英]How can I have a common variable between two methods?
boolean exists;
public void searchProduct(Vector <Stock> temp){
Scanner sc = new Scanner (System.in);
sc.useDelimiter ("\n");
exists = false;
System.out.println ("Enter Product Name to Search for: ");
String n = sc.next();
System.out.println ();
Stock s = null;
if(temp.size() == 0)
System.out.println ("Database is Empty! Please Add a Product.");
else if (!n.matches(valn))
System.out.println ("Invalid Product.Please Try Again.");
else{
for(int i = 0; i < temp.size(); i ++){
s = temp.elementAt(i);
if(s.getName().equalsIgnoreCase(n)){
System.out.println(s.ToString());
System.out.println ("Location: " + (i + 1));
exists = true;
}
}
if(exists != true)
System.out.println ("Product Not Found!");
System.out.println ("---------------------------------------------");
}
}
public void delProduct(Vector <Stock> temp){
Scanner sc = new Scanner (System.in);
if(temp.size() == 0)
System.out.println ("Database is Empty! Please Add a Product.");
else{
sc.useDelimiter("\n");
Stock s = new Stock();
int choice = 0;
int i = 0;
boolean quit = false;
boolean valid = true;
s.searchProduct(temp);
if(exists == true){
do{
try{
System.out.println ("Enter Location of Product to delete: ");
i = sc.nextInt();
temp.removeElementAt(i-1);
System.out.println ();
System.out.println ("Product was Deleted Succesfully!");
System.out.println ("--------------------------------");
valid = false;
}catch(InputMismatchException ime){
sc.next();
System.out.println ("Invalid Location.");
}catch(ArrayIndexOutOfBoundsException a){
System.out.println ("Location does not Exist!");
}
}while(valid);
}
}
}
實際上,一切都很好。 但事實是,如果用戶輸入的product name
不存在於矢量中,則仍然希望他輸入要刪除的位置。 (顯然,它正在執行應該執行的操作)。 我嘗試過聲明如果找到搜索項就將其設置為true的其他布爾變量,並且僅在布爾值為true時才執行刪除過程,但是在delete方法中,該變量始終為false。 有什么想法嗎? 順便說一句,如果我犯了愚蠢的錯誤,對不起,我還是Java的新手。
問題是,當您執行s.searchProduct(temp)
exists
,如果找到了產品,您期望它exists
,但事實並非如此。 因為在執行s.searchProduct(temp)
,您是從另一個名為s
Stock
對象中調用方法searchProduct(temp)
。 因此,如果乘積以temp exists
,則s
exists
將為真,因此s.exists
將為真。 但是,您想要真實的是this.exists
。 為此,您必須用this.searchProduct(temp)
或searchProduct(temp)
替換s.searchProduct(temp)
行。
而且據我從您的代碼了解,在delProduct
方法中,您無需創建名為s
的Stock
對象。
此外,您還可以通過首先調用selectProduct(temp)
方法來執行此刪除作業,該方法將返回產品的位置。 如果該產品不存在,則它將返回-1。 然后,如果searchProduct(temp)
方法的結果不是-1,請在deleteProduct(temp)
方法中使用返回的位置。 在這種情況下,您無需費心使用布爾標志來確定何時執行操作。 只是另一個想法。
祝好運。
調用s.searchProduct(temp)時,根據是否找到存在,存在應該變為true或false。 您是否已驗證這種情況? 您在那里的valn變量是什么?
一旦完成,您需要在delete中添加一個檢查以檢查是否存在,然后詢問位置,否則詢問更多輸入(然后再次搜索)。
您是否嘗試過聲明變量存在為volatile或靜態變量,以使其在整個類中都保持全局性。 但是它將必須使用類名進行訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.