【问题标题】:Create instance of a class that has array members创建具有数组成员的类的实例
【发布时间】:2018-11-19 23:07:21
【问题描述】:

我正在尝试创建这个对象的一个​​实例,但没有运气,我知道它是因为数组,但我怎样才能让它与数组一起工作?

public class City {
    private String Country_Name;
    private String [] Cities ;
    private String [] Destinations;}

    public City(String Country_Name, String [] Cities, String [] Destinations) {
        this.Country_Name = Country_Name;
        this.Cities = new String [2];
        this.Destinations = new String [2];
    }

    public class ASSIGNMENT {

    public static void main(String[] args) throws ParseException {
        LinkedList<FLIGHT> ob1 = new LinkedList<FLIGHT>();
        LinkedList<FLIGHT_BOOKING> ob = new LinkedList<FLIGHT_BOOKING>();
        LinkedList<City> ob3 = new LinkedList<City>();

        Scanner sc = new Scanner(System.in);
        Scanner ss = new Scanner(System.in);
        FLIGHT_BOOKING obj = new FLIGHT_BOOKING();
        FLIGHT obj1 = new FLIGHT();
        City c1 = new City("Malaysia","Kuala","Johor","melaka"},{"Cyberjaya","Putrajaya","Sunway"});
    }
}

【问题讨论】:

  • 编译错误因为}在行尾private String [] Destinations;
  • "我正在尝试创建这个对象的实例,但没有成功" - 这是什么意思?程序不能编译吗?它会抛出某种Exception吗?请在您的问题中包含编译器错误和/或异常。关于您的代码的一些注释:变量、字段和参数名称应始终以小写字母开头,并应写为camelCase --- [] 通常写在类型之后,没有空格(String [] ->String[]).
  • new City("Malaysia","Kuala","Johor","melaka"},{"Cyberjaya","Putrajaya","Sunway"}) 应该做什么?这是一个编译错误。你的意思是new City("Malaysia", new String[] { "Kuala", "Johor", "melaka" }, new String[] { "Cyberjaya", "Putrajaya", "Sunway" })
  • 仅供参考: 类名应大小写混合,即AssignmentFlightFlightBooking
  • 我正在尝试创建一个类来存储具有三个不同城市的国家/地区名称,我的问题是如何在对象实例中传递数组?

标签: java arrays object


【解决方案1】:

你放错了花括号,你在构造函数之前关闭了类定义。应该是这样的:

public class City {
    private String Country_Name;
    private String [] Cities ;
    private String [] Destinations;

    public City(String Country_Name, String[] Cities, String[] Destinations) {
        this.Country_Name = Country_Name;
        this.Cities = new String [2];
        this.Destinations = new String [2];
    }
}

另外,您错过了打开花括号。创建对象如下:

String[] cities = {"Kuala","Johor"}; // Giving only 2 cities as in constructor you've given as new String[2]
String[] destinations = {"Cyberjaya","Putrajaya"}; // Same as above
City c1 = new City("Malaysia", cities, destinations);

如果您想要更多城市和目的地,请将您的构造函数更新为

public City(String Country_Name, String[] Cities, String[] Destinations) {
            this.Country_Name = Country_Name;
            this.Cities = Cities;
            this.Destinations = Destinations;
        }

【讨论】:

    猜你喜欢
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多