If语句不适用于数组中的所有对象



我是Java编程的新手,遇到了一个问题,我认为这个问题有一个非常简单的解决方案。然而,我觉得我现在有一种狭隘的想法,似乎无法弄清楚真正的问题是什么。所以我正在制作一个程序,模拟一个鞋库,其中一个可能的操作应该是添加一只新鞋-这部分工作得很好。有一个问题是,在添加新鞋之前,应该输入鞋的产品ID,如果输入的产品ID等于现有鞋的产品标识,则应该通知用户这一点,并且不能添加具有相同产品标识的鞋。我使用的是一个if and if else语句(嵌套在for循环中,如果你这么说的话(,该语句应该在一个包含Shoe类对象的数组中运行,但if语句似乎只为数组中的第一个对象运行,它按预期工作,并通知用户已经存在具有相同产品ID的鞋,然而,如果您在数组中输入第二个或第三个对象的产品ID,程序将允许它在没有"的情况下通过;"阻塞";尽管阵列中已经存在具有该产品ID的鞋。所以我的问题是这里出了什么问题——是我的代码格式问题、拼写错误还是类似的问题?

具体情况代码:

System.out.println("Check to see if the product already exists "
+ "through entering product ID ");
shoeExists = scanObj.next();

//shoeArr is the array for Shoe object
for (Shoe shoe:shoeArr) { 
if (shoe != null && (shoe.getProdukt().equalsIgnoreCase(shoeExists))) {
System.out.println("A shoe with product ID "+shoeExists+" already exists");
System.out.println(" ");
break;  
}

else if (shoe != null && !shoe.getProdukt().equalsIgnoreCase(shoeExists)){
produktID = shoeExists;
System.out.println("Product-ID saved. Enter other details below n");
System.out.println(" ");
System.out.println("Product-ID: "+produktID);   
System.out.println("Brand: ");
brand = scanObj.next();
System.out.println("Name: ");
name = scanObj.next();
System.out.println("Model: ");
model = scanObj.next();
System.out.println("Shoe type: ");
shoeT = scanObj.next();
System.out.println("Shoe size: ");
shoeSize = scanObj.nextInt();
System.out.println("Price: ");
price = scanObj.nextInt();
System.out.println("Stock: ");
stock = scanObj.nextInt();

Shoe b_obj = new Sko(produktID, brand, name, model,
shoeT, shoeSize, price, stock);

if (counter < 20) {
shoeArr[counter] = b_obj;
counter++;

System.out.println("Shoe with product ID "+produktID+ " added");

break;
}
else {
counter = skoArr.length-1;
System.out.println("There is no room to add shoe.");

}
}
}

break;

我可能在某些地方没有使用正确的术语和语言,仍然是新手,每天都在学习。。。如上所述,这个解决方案适用于数组中的第一个对象(即预添加到数组中的对象(,但不适用于预添加到阵列中的其他两个对象,也不适用于通过这种情况添加的对象。此外,我确信这无论如何都不是解决此类问题的理想或最有效的方法,但这是我通过老师的学习材料和讲座找到的解决方案,并且最接近于工作。

如果需要更多的信息来了解问题的原因,或者如果有什么解释不好(我相信是这样的,哈哈(,请告诉我,我会尽最大努力改进。不过,我怀疑这是一些非常基本的问题。

谢谢!

您的else语句在循环中。这使得它在每次发现具有不同ID的产品时都会运行。

您应该考虑创建一个单独的contains((方法,该方法检查id是否已经存在,如果返回false,则可以注册新产品。或者,您可以在for (Shoe shoe:shoeArr)循环之前创建一个boolean found = false变量,并在数组中找到id时将其更改为true。然后,您可以将第二个if(您的else-if(移出数组,将其条件更改为!找到,并有一个工作程序。

boolean found=false;    
for (Shoe shoe:shoeArr) { 
if (shoe != null && (shoe.getProdukt().equalsIgnoreCase(shoeExists))) {
System.out.println("A shoe with product ID "+shoeExists+" already exists");
System.out.println(" ");
break;  
}

}
if (!found){
produktID = shoeExists;
System.out.println("Product-ID saved. Enter other details below n");

最新更新