gpt4 book ai didi

java - 如何将对象添加到 vector 中?

转载 作者:行者123 更新时间:2023-11-29 08:52:28 24 4
gpt4 key购买 nike

问题是——将航类的详细信息作为输入,创建对象 Ticketvector。请注意,门票应以与输入相同的顺序出现在 vector 中。详细信息已作为 String[] 提供。数组中的每一项都对应一张机票,并具有以下空格分隔的详细信息:Origin, destination, departure, arrival, amount

我尝试跟随,但由于我是新手,而且我是第一次这样做,所以我找不到自己的路。

   import java.util.Vector;

public class FlightTickets {

String origin;
String destination;
String departure;
String arrival;
String amount;
Vector v = new Vector();

public FlightTickets(String origin, String destination, String departure, String arrival, String amount) {
this.origin = origin;
this.destination = destination;
this.departure = departure;
this.arrival = arrival;
this.amount = amount;
}

public static void main(String[] args) {
FlightTickets ticket = new FlightTickets("Caledonia", "South Korea", "10:00", "5:00", "15000");
v.add(ticket);
}
}

最佳答案

试试这个:

public static void main(String[] args) {           
FlightTickets ticket = new FlightTickets("Caledonia", "South <bKorea", "10:00", "5:00", "15000");
ticket.v.add(ticket);
}

请记住,您不能从静态方法访问非静态变量。顺便说一句,由于 Vector 类是泛型类型,因此最好像这样定义“v”:

Vector<TestClass> v = new Vector<TestClass>();

作为对您评论的回应,我提供了一个相当完整的实现以获取更多详细信息:

import java.util.Iterator;
import java.util.Vector;

public class TestClass {

String Origin;
String destination;
String departure;
String arrival;
String amount;
Vector<TestClass> v = new Vector<TestClass>();

public TestClass(String Origin, String destination, String departure, String arrival, String amount) {
this.Origin = Origin;
this.destination = destination;
this.departure = departure;
this.arrival = arrival;
this.amount = amount;
}

public static void main(String[] args){
TestClass ticket = new TestClass("Caledonia", "South Korea", "10:00", "5:00", "15000");
ticket.v.add(ticket);
Iterator<TestClass> it = ticket.v.iterator();
while(it.hasNext())
System.out.println(it.next().Origin);
}
}

关于java - 如何将对象添加到 vector 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22077253/

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