gpt4 book ai didi

java - 使用JAVA对象和输入数据进行赋值

转载 作者:太空宇宙 更新时间:2023-11-04 11:20:57 24 4
gpt4 key购买 nike

所以我的任务是创建一个名为 city 的对象,并具有城市的经度、纬度和名称,然后询问城市的数量,然后用户将名称、经度和纬度输入到数组中进行访问。我将如何利用我现在所拥有的来实现这一目标?

import java.util.Scanner;

public class Assignment3 {

public static void main(String[] args) {

Scanner lat = new Scanner(System.in); //for double data
Scanner lon = new Scanner(System.in); //for double data
Scanner city = new Scanner(System.in); //for string data
Scanner in = new Scanner(System.in); //for int

System.out.print("How many cities? ");
int number = in.nextInt();


City [] cities = new City [number];

for(int i = 1; i <= number; i++){

System.out.println("City # " + i);
System.out.print("Enter name: " );
String name = city.Next();
System.out.print("Enter longitude: ");
double longitude = lon.nextDouble();
System.out.println("Enter latitude: ");
double latitude = lat.nextDouble();

}

}

}


public class City {

String name; //name of cities
double lon, lat; //longitude & latitude

City(String name, double lon, double lat)
{
this.name = name;
this.lon = lon;
this.lat = lat;
}




public void report(){ //should report current position of a city

System.out.println("City: " + this.name); // displays city name
System.out.println("Longitude: " + this.lon); //displays longitude
System.out.println("Latitude: " + this.lat); //displays latitude
}

public double distanceFrom(City otherCity){ //should calculate the distance
return 0;
}
}

重点是,您可以询问城市的直接位置以及它们之间的距离。非常感谢任何帮助,谢谢

最佳答案

您可以通过这种简单的方法实现这一点:

为您希望用户输入的每个属性定义 City 类的 setter 实例方法,然后在主程序中迭代城市的每个对象并设置其信息:

public static void main(String[] args) {

Scanner input = new Scanner(System.in);
System.out.print("How many cities? ");
int number = input.nextInt();
City [] cities = new City [number];
for(int i = 0; i < number; i++){
cities[i] = new City(); // create new object of City
System.out.println("City # " + (i+1));
System.out.print("Enter name: " );
String name = input.next();
cities[i].setName(name);
System.out.print("Enter longitude: ");
double longitude = input.nextDouble();
cities[i].setLongitude(longitude);
System.out.print("Enter latitude: ");
double latitude = input.nextDouble();
cities[i].setLatitude(latitude);
}
}

public class City {

private String name; //name of cities
private double lon, lat; //longitude & latitude

City(){ // default constructor
name="";
this.lon = 0;
this.lat = 0;
}

City(String name, double lon, double lat)
{
this.name = name;
this.lon = lon;
this.lat = lat;
}

public void setName(String n){
name = n;
}
public void setLongitude(double longitude){
lon = longitude;
}
public void setLatitude(double latitude){
lat = latitude;
}
}

关于java - 使用JAVA对象和输入数据进行赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44913978/

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