This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
I am having trouble with a beginner java project. The user enters a value which I need to pass to the FlightSeatReservation class in its constructor. I then need to use that value in the creation of a two dimensional array. I initialize this value, the "rows" value, in the FlightSeatReservation class to 0. I then try to change this to the user-entered value in the constructor. I believe the array is being created with a value of 0 instead of the user-entered value for rows. If I manually enter a number where "rows" is (...new String) the entire program works fine. I figured when the object was created, the rows value would be changed and the array would be initialized using the new value. Any suggestions would be greatly appreciated.
The way I would fix it is by changing your constructor. You could get rid of rows variable altogether, and initialize (or declare, not sure how to word it, it's late) the new array inside of it.
Knowing that you're going to passing in the amount of rows to your constructor, you could just put that into the [rows] dimension.
Da mihi sis bubulae frustum assae, solana tuberosa in modo Gallico fricta ac quassum lactatum coagulatum crassum.
Kyle Floros wrote:I figured when the object was created, the rows value would be changed and the array would be initialized using the new value. Any suggestions would be greatly appreciated.
Well, first off I agree with Aj: initialize your array in a method, and pass it back to your program. Don't overthink things.
Second: while you've split your program into methods nicely, you're mixing up content with display. Your seat array could be many things, but the one thing it should NOT be is a String.
I know why you did it - because you want it to contain the values you're going to display - but it's a bad way of designing. Much better to have it hold values that make sense for a seat, and translate those values into Strings when you want to display.
Remember this mantra: Strings are BAD.
That is to say: Strings should only be used to contains strings of characters; they make bad substitutes for other types.
Obviously, there may be occasions where you need to accept them as input (eg, your 'number of rows'), but you should convert them to the appropriate type (an int) as soon as you possibly can.
In your case, you have a perfectly good alternative for your array: create a Seat class. You can then give it a proper 'status' field (EMPTY or RESERVED) and use its toString() method to display it any way you like. That's how Object-orientation works.
Furthermore, your seat array then becomes:
Seat seats; and isn't that a lot clearer?
Isn't it funny how there's always time and money enough to do it WRONG?
Artlicles by Winston can be found here