[英]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.