嘿伙计们我正在尝试编写一个类,我的课程中的一个方法是假设搜索一个数组,查找其产品项目由我给出的第3个参数。我有2个问题。
public static int ProductSearch(GroceryItems[] product, int numProducts, int productNumber)
答案 0 :(得分:0)
您是否正在寻找POJO类的任何属性匹配。
在这个例子中,如果找不到attr,那么将需要-1。
public static void main(String[] args) {
// TODO code application logic here
GroceryItems[] GroceryItems = new GroceryItems[]{new GroceryItems(5), new GroceryItems(22), new GroceryItems(45), new GroceryItems(95)};
int ProductSearch = ProductSearch(GroceryItems, 5, 67);
System.out.println(ProductSearch);
}
public static int ProductSearch(GroceryItems[] product, int numProducts, int productNumber) {
for (int i = 0; i < product.length; i++) {
if (product[i].productNumber == productNumber) {
return i + 1;
}
}
return -1;
}
private static class GroceryItems {
int productNumber;
public GroceryItems() {
}
public GroceryItems(int productNumber) {
this.productNumber = productNumber;
}
}
答案 1 :(得分:0)
import java.util.ArrayList; import java.util.List;
公共类ProdSearch {
public static void main(String[] args) {
List<GroceryItems> prods = new ArrayList<GroceryItems>();
GroceryItems p1 = new GroceryItems();
p1.setProductNumber(1);
prods.add(p1);
GroceryItems p2 = new GroceryItems();
p2.setProductNumber(4);
prods.add(p2);
GroceryItems p3 = new GroceryItems();
p3.setProductNumber(1);
boolean res = productContains(prods, 123, p3);
if (res) {
System.out.println("Contains..");
} else {
System.out.println("No such an element..");
}
}
public static boolean productContains(List<GroceryItems> product, GroceryItems productSearch) {
return product.contains(productSearch);
}
}
class GroceryItems { int productNumber;
public int getProductNumber() {
return productNumber;
}
public void setProductNumber(int productNumber) {
this.productNumber = productNumber;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + productNumber;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
GroceryItems other = (GroceryItems) obj;
if (productNumber != other.productNumber)
return false;
return true;
}
}
答案 2 :(得分:0)
public static int productSearch(GroceryItems [] products,int numProducts,int productNumber){
boolean found = false;
int i = 0;
if (products == null ||
products.length != numProducts ||
numProducts < 1))
return -1;
while (!found && i < numProduct) {
if (products[i].productNumber == productNumber)
found = true;
else i++;
}
if (!found)
i = -1;
return i;
}