我目前正在研究程序的一部分,该程序会提示用户将新巡航添加到现有巡航列表中。当前列表如下:
public static void initializeCruiseList() {
Cruise newCruise = new Cruise("Southern Swirl", "Candy Cane", "Miami", "Cuba", "Miami");
cruiseList.add(newCruise);
Cruise newCruiseTwo = new Cruise("Hippy Train", "Ole Bertha", "Baltimore", "The 70s", "Baltimore");
cruiseList.add(newCruiseTwo);
}
我遇到的问题是“ addCruise”的“船名”部分的输入,需要检查以确保Ship已经存在,还需要检查该船是否在服役中,并且该船舶在shipList中以布尔值形式存在。发货清单如下:
public static void initializeShipList() {
add("Candy Cane", 20, 40, 10, 60, true);
add("Peppermint Stick", 10, 20, 5, 40, true);
add("Bon Bon", 12, 18, 2, 24, false);
add("Candy Corn", 12, 18, 2, 24, false);
}
我遇到的问题是将“ addCruise”方法中的用户输入与飞船名称和布尔变量进行比较,考虑到用户仅输入了字符串。目前,这是我所拥有的:
System.out.println("Enter ship name: ");
String newShipName = newCruiseInput.nextLine();
for(Ship eachShip: shipList) {
if((eachShip.getShipName() != newShipName) && (eachShip.getInService() == false)) {
System.out.println("This ship doesn't exist or isn't in service.");
return;
}
}
我很确定当前设置的问题在于它遍历整个列表,无论如何,它总是会找到一个“ false”的条目,使代码的行为就像用户输入了无效的条目,即使他们没有。因此,我该如何在条目中查找船名,然后检查以确保所选船当前正在服役?如果您需要除此以外的更多信息,请询问,我将尽力提供更多信息。
尝试使用标志
boolean shipFound = false;
for(Ship eachShip: shipList) {
if((eachShip.getShipName().equals(newShipName)) && (eachShip.getInService() == true)) {
shipFound=true;
break;
}
}
if(shipFound)
// Do what you want
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句