我有這個任務,我試圖編碼,但不幸的是,這給我一個很難。Java封裝的陣列增變器方法
我搜索了互聯網和我的教科書,但似乎無法找到這種特殊困境的例子。
基本上,我需要爲火車編寫預訂引擎,我們獲得了我們打算使用的啓動代碼,並基本寫出我們的方法並將它們插入相應的類。
主要問題是我們需要封裝主要數組來保存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);
}
驅動程序類所以基本上,我ahve沒有問題編寫代碼請求的各個細節形成用戶,然後使用該構造函數調用instatiating對象爲TrainTicket對象, 當我沿着使用
TicketArray.add(ticketx);
蝕通知對象陣列類傳ŝ我「不能讓一個靜態引用從類型TicketArray非靜態方法Add(TrainTicket)」
這是Array類的樣子
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;
}
任何想法,爲什麼它不工作? 我會很感激,如果有人可以解釋如何以這種方式封裝數組,我熟悉構造函數的工作方式和他們的方法編寫的方式,但出於某種原因,我發現很難做同樣的事情陣列。
在此先感謝。
你爲了調用一個實例方法需要一個實例。這個問題與數組無關。 –
嗨戴夫,你能澄清一下嗎?一個什麼樣的實例? – user1405824
TicketArray,您正試圖調用實例方法的類。或者,你可以使它成爲一個靜態的方法,但是,海事組織。 –