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

66bbxpm5  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(393)

我对java编程非常陌生,遇到了一个问题,我认为这个问题有一个非常简单的解决方案。然而,我觉得我现在有隧道的眼光,似乎不能明白问题到底是什么。所以我要做一个程序来模拟一个鞋类仓库,其中一个可能的操作应该是添加一个新鞋-这部分工作得很好。在添加新鞋之前,需要输入鞋的产品id,如果输入的产品id等于现有鞋的产品id,应该通知用户这一点,并且不能添加具有相同产品id的鞋。我正在使用if和if else语句(嵌套在for循环中,如果你这么说的话),该语句应该在包含鞋类对象的数组中运行,但似乎if语句只对数组中的第一个对象运行,如果它按预期工作,并通知用户具有相同产品id的鞋已经存在,但是如果您在数组中输入第二个或第三个对象的产品id,程序将允许该产品id通过,而不会“阻止”用户添加它,尽管具有该产品id的鞋已经存在于数组中。所以我的问题是这里出了什么问题-是不是我的代码格式有问题,打字错误,或者类似的问题?
具体情况代码:

  1. System.out.println("Check to see if the product already exists "
  2. + "through entering product ID ");
  3. shoeExists = scanObj.next();
  4. //shoeArr is the array for Shoe object
  5. for (Shoe shoe:shoeArr) {
  6. if (shoe != null && (shoe.getProdukt().equalsIgnoreCase(shoeExists))) {
  7. System.out.println("A shoe with product ID "+shoeExists+" already exists");
  8. System.out.println(" ");
  9. break;
  10. }
  11. else if (shoe != null && !shoe.getProdukt().equalsIgnoreCase(shoeExists)){
  12. produktID = shoeExists;
  13. System.out.println("Product-ID saved. Enter other details below \n");
  14. System.out.println(" ");
  15. System.out.println("Product-ID: "+produktID);
  16. System.out.println("Brand: ");
  17. brand = scanObj.next();
  18. System.out.println("Name: ");
  19. name = scanObj.next();
  20. System.out.println("Model: ");
  21. model = scanObj.next();
  22. System.out.println("Shoe type: ");
  23. shoeT = scanObj.next();
  24. System.out.println("Shoe size: ");
  25. shoeSize = scanObj.nextInt();
  26. System.out.println("Price: ");
  27. price = scanObj.nextInt();
  28. System.out.println("Stock: ");
  29. stock = scanObj.nextInt();
  30. Shoe b_obj = new Sko(produktID, brand, name, model,
  31. shoeT, shoeSize, price, stock);
  32. if (counter < 20) {
  33. shoeArr[counter] = b_obj;
  34. counter++;
  35. System.out.println("Shoe with product ID "+produktID+ " added");
  36. break;
  37. }
  38. else {
  39. counter = skoArr.length-1;
  40. System.out.println("There is no room to add shoe.");
  41. }
  42. }
  43. }
  44. break;

我可能还没有使用正确的术语和语言在一些地方,仍然是新的这一点和学习的一天。。。正如我上面提到的,这个解决方案适用于数组中的第一个对象(即预添加到数组中的对象),但不适用于预添加到数组中的其他两个对象,也不适用于通过这种情况添加的对象。我也确信这不是解决这类问题的最理想或最有效的方法,但这是我通过学习材料和老师的讲课找到的解决方法,并且离工作最近。
如果需要更多的信息来了解是什么导致了问题,或者如果有些事情解释得不好(我确信是这样的lol),请告诉我,我会尽我所能来改进。我怀疑是一些非常基本的东西出了问题。
谢谢!

nfzehxib

nfzehxib1#

你的else语句在循环中。这使得它在每次找到具有不同id的产品时都会运行。
您应该考虑创建一个单独的contains()方法来检查id是否已经存在,如果它返回false,您可以注册新产品。或者,您可以创建 boolean found = false 就在你的 for (Shoe shoe:shoeArr) 循环,并将其更改为 true 当您在数组中找到id时。然后你可以把第二个if(你的else if)移出数组,把它的条件改为!找到了,并且有一个工作程序。

  1. boolean found=false;
  2. for (Shoe shoe:shoeArr) {
  3. if (shoe != null && (shoe.getProdukt().equalsIgnoreCase(shoeExists))) {
  4. System.out.println("A shoe with product ID "+shoeExists+" already exists");
  5. System.out.println(" ");
  6. break;
  7. }
  8. }
  9. if (!found){
  10. produktID = shoeExists;
  11. System.out.println("Product-ID saved. Enter other details below \n");

相关问题