【问题标题】:Set of cities in Java [duplicate]Java中的一组城市[重复]
【发布时间】:2021-02-20 08:24:15
【问题描述】:

在我的任务中,我已经排列了一些城市,但我现在面临一个问题。

我主要是这样做的:

City[] cities = enterCity(scanner);

在输入城市的方法中,我有 3 个数组。所以我需要返回城市名称和公民人数。 在 for 循环中,我输入姓名和公民人数。在循环结束时,我这样做了:

cities[i]=new City(name, numbersOfCitizens);

然后用 City[] 城市返回它。 现在我需要用 set 改进我的代码。

在我实现的方法中:

Set<City> cities = new Hashset<>();

我未能创建方法添加。我试着用这个在 main 中调用它:

add.(City(name, numbersOfCitizens));

在 City 类中并返回 City[] 城市表示不可转换的类型(因此它不能返回任何内容)。像我在 main 中那样调用方法是否正确,以及如何正确返回所有值。在 City 类中,我通常使用 get 和 set 方法。

【问题讨论】:

标签: java set


【解决方案1】:

创建Set

// Create new Set 
Set<City> cities = new HashSet<City>();

// Add new City
cities.add(new City());

Set 转换为数组 - 选项 #1

City[] objects = cities.toArray(new City[0]);

Set 转换为数组 - 选项 #2

手动复制:

City[] objects = new City[cities.size()];
int position = 0;

for (City city : cities) {
    objects[position] = city;
    position++;
}

工作示例

public class SetExample {

    private static Scanner scanner;

    public static void main(String[] args) {
        scanner = new Scanner(System.in);

        Set<City> cities = readCities();
    }

    private static Set<City> readCities() {
        Set<City> cities = new HashSet<City>();
        int numberOfCities = 3;

        for (int i = 0; i < numberOfCities; i++) {
            City newCity = readCity();
            cities.add(newCity);
        }

        return cities;
    }

    private static City readCity() {
        System.out.print("Name: ");
        String name = scanner.nextLine();

        System.out.print("Numbers of citizens: ");
        int numbersOfCitizens = scanner.nextInt();

        return new City(name, numbersOfCitizens);
    }
}

打印

类示例:

class City {
    private String name;
    private int numbersOfCitizens;

    public City(String name, int numbersOfCitizens) {
        this.name = name;
        this.numbersOfCitizens = numbersOfCitizens;
    }
}

当你将使用不添加toString() 方法时:

City city = new City("New York", 1234);
System.out.println(city);

你可以期待输出:

City@19469ea2

要打印自定义消息,您必须重写 toString() 方法,例如在 IntelliJ 中生成“默认”方法:

@Override
public String toString() {
    return "City{" +
            "name='" + name + '\'' +
            ", numbersOfCitizens=" + numbersOfCitizens +
            '}';
}

或类似的简单的东西:

@Override
public String toString() {
    return name + " " + numbersOfCitizens;
}

【讨论】:

  • 谢谢,这对我帮助很大。
  • @Qyz 添加了更多相关信息 :)
  • 已解决,现在我面临如何访问诸如 city[i].name 但集合没有索引的问题。我会花一些时间来完成这项任务:)
  • 所以用List&lt;City&gt;代替Set&lt;City&gt;(例如ArrayList
  • 对于城市我必须使用 Sets。
猜你喜欢
  • 2016-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-21
  • 2012-02-24
相关资源
最近更新 更多