[英]Java: How to call method of a class in another method of the same class?
[英]How to call a method in another method in Java (same class)
我試圖從同一個類中的另一個方法調用一個方法,以檢查用戶輸入的內容是否在arrayList中。 如果它在arrayList中,我想在其數量上加1。 如果它不在arrayList中,則將其添加到arrayList中。 這是我所擁有的:
public Item searchForItem(String n){
for(int i = 0; i < s.size(); i++){
Item y = s.get(i);
if(y.getName().equals(name)){
return y;
}
}
return null;
}
public void addItem(Item f) {
s.add(f);
}
我知道在addItem
方法中需要if語句,但是我不確定如何編寫它。
有沒有辦法檢查是否返回了y
或是否返回了null
?
只需調用將名稱作為參數傳遞的searchForItem方法即可。
public void addItem(Item f) {
if(searchForItem(f.getName())==null) {
s.add(f); // add's the item only if searchForItem returns null
}
}
使用foreach語法獲取更簡單的代碼,然后嘗試執行以下操作:
public Item searchForItem(String name){
for(Item y : s) {
if(y.getName().equals(name)){
return y;
}
}
s.add(new Item(name));
return null;
}
使用HashMap! 它將具有O(1)訪問時間,因此您不必迭代數組列表。 使用containsKey方法檢查元素是否在地圖中,並使用get方法獲取它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.