我遇到了一個問題,用戶應該(通過掃描儀)輸入物件的 ID。它應該是我為“ff”串列中的每個產品(1234 或 5678 或 9012 或 2345 或 7890)輸入的 4 位數字之一。如果他們輸入了一個不在串列中的數字(ID),它應該輸出一個句子告訴用戶他們犯了一個錯誤。
無論我在控制臺上輸入什么,我都會得到"You've made a mistake! There's no product with such ID!"輸出。即使我輸入了我串列中的數字。
System.out.println("I'm displaying boots:\n");
List<FemaleFootwear> ff = new ArrayList<FemaleFootwear>();
ff.add(new FemaleFootwear(1234, "Boots 1", 180));
ff.add(new FemaleFootwear(5678, "Boots 2", 190));
ff.add(new FemaleFootwear(9012, "Boots 3", 150));
ff.add(new FemaleFootwear(3456, "Boots 4", 140));
ff.add(new FemaleFootwear(7890, "Boots 5", 220));
System.out.println(ff);
System.out.println("For shopping type 1, for going back to the menu type 2.");
int option = sc.nextInt();
if (option == 1) {
System.out.println("Please enter the product ID:\n");
int option2 = sc.nextInt();
if (option2 == ff.indexOf(0)) {
while (ff.contains(option2)){
System.out.println("You've chosen the product " option2);
}
}else {
System.out.println("You've made a mistake! There's no product with such ID!");
}
}
例如,如果我輸入“1234”,即名為“Boots 1”的產品,輸出應該是“您選擇了產品 1234”。但是,如果我輸入串列中不存在的數字(或字母),它應該會顯示此錯誤。
uj5u.com熱心網友回復:
indexOf(Object o)要求您提供串列中包含的實際物件。為了在串列中搜索物件(包括 with .contains()),您需要在您的類上實作equalsand hashcode...
我認為您的意思是ff.get(0), not ff.indexOf(0),甚至仍然不能使用==, or將整數與串列中的物件進行比較.equals(),因為這永遠不會匹配。
相反,您需要通過他們的 ID 搜索串列,并且不需要 while 回圈。
System.out.println("Please enter the product ID:\n");
int option2 = sc.nextInt();
Optional<FemaleFootwear> search = ff.stream()
.filter(footwear -> footwear.getID() == option2)
.findFirst();
if (search.isPresent()) {
System.out.println("You've chosen the product " option2);
} else {
System.out.println("You've made a mistake! There's no product with such ID!");
}
請記住,以任何前導零開頭的“4 位數字”不是“4 位數字”,因此您可能不想使用整數來表示它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/485490.html
