Firstly, my apologies for my weak knowledge of Java and its terminology. I'll do my best. I'm trying to sort the array below, eventStuff
, by the variables stored within the array. I am giving the user three options to choose from, an event number (Letter, number x 3), the number of guests entered (between 5 and 100, including), and an event type (1 to 4, including). I am currently suffering a complete mental block on how to do this. Have I set up the array incorrectly, or is there an easier way to do this using what I've got so far? Thank you for the assistance!
Update: So I've got a handle on all the numeric sorting, but the alphanumeric (e.g. A111) eventCodeString
is beyond me. I have checked several forums and applied many reasonable solutions, but they are either ineffective or throw an error. I am unsure of what I should do, at this point.
package Chapter9;
import Chapter9.Event;
import javax.swing.JOptionPane;
import java.util.Arrays;
public class EventDemo
{
public static void main(String[] args)
{
callMotto();
int x;
Event[] eventStuff = new Event[8];
for(x = 0; x < 8; ++x)
{
eventStuff[x] = new Event();
eventStuff[x].setEventCodeString();
eventStuff[x].setGuests();
eventStuff[x].setContactNumber();
eventStuff[x].setEventStr();
}
//Sorting method start
String sorting;
int sortMethod;
sorting = JOptionPane.showInputDialog("Please chooose sorting method:\n"
+ "1 to sort by event number\n"
+ "2 to sort by number of guests\n"
+ "3 to sort by event type");
sortMethod = Integer.parseInt(sorting);
//Event number sorting start
if(sortMethod == 1)
{
}
//Event number sorting end
//Event guest sorting Start
if(sortMethod == 2)
{
}
//Event guest sorting end
//Event type sorting start
if(sortMethod == 3)
{
}
//Event type sorting end
//Sorting method end
}
public static void callMotto()
{
JOptionPane.showMessageDialog(null, "*******************************************************\n"
+ "* Carly's Makes The Food That Makes The Party! *\n"
+ "*******************************************************");
}
}
For example, if you want to sort your array over number of guests, you can use something like that:
I suppose that
getGuests
returns the number of guests.Use the
Arrays.sort()
that takes aComparator
, then, depending on the selection, create aComparator<Event>
that compares twoEvent
s based on the selected sort key, e.g.:Then, if the user selects event number:
Or, e.g.:
Or any one of many possible versions of the above; point being that a
Comparator
compares twoEvent
s based on some key, and you then use thatComparator
to define the sort order of the array. Create a copy of the array first and sort that if you'd rather not sort in place, although it seems like that will be fine for your application. You can also use containers, e.g. anArrayList
, if you'd like.Check out the official tutorial on comparators (see the comparator section towards the bottom, not the "comparable" part at the top).