gpt4 book ai didi

java - 程序不会打印语句

转载 作者:行者123 更新时间:2023-12-02 03:36:48 25 4
gpt4 key购买 nike

我有一个程序,我在其中选择一个选项来添加船舶,这会提示我提供一个 ID,例如 b 2。然后它会提示我输入容量。但是,我正在使用搜索方法来防止我可能第二次输入任何重复的 ID。程序可以编译,但我的语句“Ship id is already in use”不会打印出来。请问有什么想法吗?

这是我的代码。

public int search(String id)
{
for(int index = 0; index < ships.length && ships[index] != null; ++index)
{
shipId = id;
if (ships[index].getId().equals(id))
{
return index;
}
}
//ship id not found so you can add ship
return -1;
}

public void addShip( )
{
System.out.println("Enter ship id >> ");
String id = kb.nextLine();
if(id.equals(search(id)))
{
System.out.println("Ship id already in use");
return;
}


else
{
//for(int i = 0; i < ships.length; ++i)
{
System.out.println("Enter ship capacity");
int capacity = kb.nextInt();
ships[shipCounter++] = new Ship(id, capacity);
}
}
}

这是我的船级:

public class Ship
{
private String id;
private int capacity;
private int currentCrew; // index into the Crew array
// points to the next free space
// in the Crew array
private String status;

private Crew [ ] crew;

public Ship(String id, int capacity)
{
this.id = id;
this.capacity = capacity;
this.currentCrew = 0;
crew = new Crew[capacity];

}
public Ship(String id, int capacity, String status)
{
this.id = id;
this.capacity = capacity;
this.status = "available";
this.currentCrew = 0;
crew = new Crew[capacity];

}
public void setId(String newId)
{
id = newId;
}
public void setCapacity(int newCapacity)
{
capacity = newCapacity;
}
public void setStatus(String newStatus)
{
if(status.equals("available"))
{
newStatus = "on station";
status = newStatus;
}
else if(status.equals("on station"))
{
newStatus = "maintenance";
status = newStatus;
}
else if(status.equals("station") || status.equals("maintenance"))
{
newStatus = "available";
status = newStatus;
}
else
{
System.out.println("Invalid status");
}
}
public String getId()
{
return id;
}
public String getStatus()
{
return status;
}
public int getCapacity()
{
return capacity;
}
public int getCurrentCrew()
{
return currentCrew;
}
public void addCrew()
{
//if(currentCrew < capacity)
{
//System.out.println("Enter crew id >> ");
//String id = kb.nextLine();
}
}

public String toString()
{

String sdesc =
'\n'
+ "Ship"
+ '\n'
+ "["
+ '\n'
+ " "
+ "Id: " + id
+ " capacity: " + capacity
+ " current crew: " + currentCrew
+ " status: " + status
+ '\n'
+ "]";

return sdesc;
}
}

最佳答案

你注意到这一行了吗

 if(id.equals(search(id)))

id是String类型,但search返回类型是int。

如果您在String类中看到equals方法,

 if (anObject instanceof String) {

}
return false;

所以它总是给出错误

所以简单的解决方案是将 int 转换为 String。类似的东西

if(id.equals(search(id+"")))

关于java - 程序不会打印语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37364310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com