[英]Java encapsulated Array mutator method
我有这个任务,我正在尝试编码,但不幸的是,它给了我一个艰难的时间。
我已经浏览了互联网和我的教科书,但似乎无法找到这种特殊困境的例子。
基本上,我需要为火车写一个预订引擎,我们给了我们打算使用的启动代码,基本上写出我们的方法并将它们插入适当的类。
主要问题是我们需要将包含trainticket对象的主数组封装在一个单独的类中,并且基本上编写mutator和accessor方法,需要与数组进行任何交互,以保持数组在访问时不可访问和安全。需要。
这是该程序的驱动程序类
Private static void menuAdd()
{
String passName,op1,op2;
int seatNum;
Boolean FCOption,waiter,indicator;
int duration;
char fClass,wService;
System.out.print("Please Enter a seat number :");
seatNum = stdin.nextInt();
stdin.nextLine();
System.out.print("Please Enter the passenger name :");
passName = stdin.nextLine();
System.out.print(passName);
System.out.print("Please Enter number of legs for this trip :");
duration = stdin.nextInt();
System.out.println("Would you like to consider a First Class ticket for an additional $20 per leg? :");
System.out.print("Please enter Y/N");
op1 = stdin.next();
fClass =op1.charAt(0);
stdin.nextLine();
System.out.print("Would you like to consider a waiter service for a flat $15 Fee?");
System.out.print("Please enter Y/N");
op2 = stdin.next();
wService =op2.charAt(0);
//Now we create the ticket object
TrainTicket ticketx = new TrainTicket(seatNum,passName,duration);
System.out.println("This is an object test printing pax name"+ticketx.getName());
TicketArray.add(ticketx);
}
所以基本上,我没有问题编写代码请求用户的各种细节,然后使用构造函数调用TrainTicket对象来实例化对象,当我使用对象传递给数组类时
TicketArray.add(ticketx);
eclipse告诉我“无法从TicketArray类型中对非静态方法添加(TrainTicket)进行静态引用”
这就是数组类的样子
Public class TicketArray
{
// ..............................................
// .. instance variables and constants go here ..
// ..............................................
int counter ;
int arraySize =100 ;
// constructor
public TicketArray()
{
// ....................
// .. implement this ..
// ....................
TrainTicket [] tickets =new TrainTicket[arraySize];
}
// add() method:
// take the passed in TrainTicket object and attempt to store it in the
// data structure. If the structure is full, or the seat of the given
// TrainTicket has already been booked, the operation should return
// false; otherwise return true.
public boolean add(TrainTicket data)
{
// ....................
// .. implement this ..
// ....................
tickets[counter]=data;
// dummy return value so the skeleton compiles
return false;
}
任何想法为什么它不起作用? 我很感激如果有人能解释如何以这种方式封装数组,我熟悉构造函数的工作方式和编写方法,但由于某种原因,我发现很难用数组做同样的事情。
提前致谢 。
这里的问题不是使用mutator或accessor方法甚至是数组,而是在尝试使用它之前不创建TicketArray
类的实例。 add(Ticket t)
被定义为一个实例方法,这意味着您需要先添加TicketArray
实例才能添加它。
尝试这个:
//create a new Ticket
TrainTicket ticketx = new TrainTicket(seatNum,passName,duration);
//create a new Ticket Array
TicketArray tarr = new TicketArray();
tarr.add(ticketx);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.