gpt4 book ai didi

java - 将一种方法从一个类实现到另一个类?

转载 作者:行者123 更新时间:2023-12-02 07:08:30 24 4
gpt4 key购买 nike

我正在为一个类(class)制作一个飞机座位安排程序,我最终制作了两个 toString 方法,但是当我运行该程序时,我的飞机类(class)中的 toString 方法正在使某些东西无法具体工作:

str= str + seats[i][j].toString();

我相信,只需删除座位类中的 toString 方法,然后以某种方式将其放回飞机类 toString 方法中,就可以解决问题或使其变得更简单。怎么了?

飞机等级:

public class Airplane 
{
private Seat [ ] [ ] seats;
public static final int FIRST_CLASS = 1;
public static final int ECONOMY = 2;
private static final int FC_ROWS = 5;
private static final int FC_COLS = 4;
private static final int ECONOMY_ROWS = 5;
private static final int ECONOMY_COLS = 6;

public Airplane()
{
seats = new Seat[FC_ROWS][ECONOMY_COLS];
}
public String toString()
{
String str = "";
for (int i=0; i<FC_ROWS; i++) {
for (int j=0; j<ECONOMY_COLS; j++)
{
str= str + seats[i][j].toString();
}
str = str + "\n";
}
return str;
}

}

座位等级:

public class Seat 
{
private int seatType;
private boolean isReserved;
public static final int WINDOW = 1;
public static final int AISLE = 2;
public static final int CENTER = 3;

public Seat(int inSeatType)
{
seatType = inSeatType;
isReserved = false;
}
public int getSeatType()
{
return seatType;
}

public void reserveSeat()
{
isReserved = true;
}
public boolean isAvailable()
{
if (!isReserved)
{
return true;
}
else return false;
}
public String toString()
{
if(isReserved == false)
{
return "*";
}
else return "";
}
}

最佳答案

  • Seat.toString 中,您应该打印 "" 而不是 ""
  • 您的数组为 FC_ROWS by ECONOMY_COLS,因此您并未创建所有席位。您可能应该有两个数组(一个用于 FC,一个用于经济),因为 FC_ROWS != ECONOMY_ROWS
  • 您实际上并未在构造函数中创建 Seat。使用嵌套循环来创建它们,否则您将得到 NullPointerException。创建数组不会创建数组中包含的对象。
    • 当您在 Airplane 构造函数中创建座位时,请使用 if 语句来确定座位是否应该是靠窗、过道等。

关于java - 将一种方法从一个类实现到另一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15825990/

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