Reputation: 170
I have to sort a list of objects by the date provided in them. My initial thought was to use a switch case. But that means a maximum of 31 cases. Here is the code im using:
if (e.getSource() == btnSalesPerDay)
{
//int i =0;
SalesTextArea.setText("");
Object[] possibilities = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"};
String dayOption = (String)JOptionPane.showInputDialog(frame,"Pick a day you wish to display the records for : ", "Catagory pick", JOptionPane.PLAIN_MESSAGE, null, possibilities,"ham");
switch(dayOption)
{
case 1:
if(salesdata[i].day == 1)
{
int i =0;
while (salesdata != null)
{
SalesTextArea.insert("\t" + salesdata[i].totalPrice, 0);
SalesTextArea.insert("\t" + salesdata[i].year, 0);
SalesTextArea.insert("\t" + salesdata[i].month, 0);
SalesTextArea.insert("\t" + salesdata[i].day, 0);
SalesTextArea.insert("\t" + salesdata[i].customerName, 0);
SalesTextArea.insert("\t" + salesdata[i].salesNo, 0);
SalesTextArea.insert("\n", 0);
i++;
}
}
break;
case 2:
if(salesdata[i].day == 2)
{
int i =0;
while (salesdata != null)
{
SalesTextArea.insert("\t" + salesdata[i].totalPrice, 0);
SalesTextArea.insert("\t" + salesdata[i].year, 0);
SalesTextArea.insert("\t" + salesdata[i].month, 0);
SalesTextArea.insert("\t" + salesdata[i].day, 0);
SalesTextArea.insert("\t" + salesdata[i].customerName, 0);
SalesTextArea.insert("\t" + salesdata[i].salesNo, 0);
SalesTextArea.insert("\n", 0);
i++;
}
}
break;
It goes on up to the 31 cases.. My question is.. is there a simpler way? Whats the most efficient way to go about this?
Thanks :)
Upvotes: 0
Views: 74
Reputation: 692171
You just need a single loop:
String dayOption = (String)JOptionPane.showInputDialog(frame,"Pick a day you wish to display the records for : ", "Catagory pick", JOptionPane.PLAIN_MESSAGE, null, possibilities,"ham");
int chosenDay = Integer.parseInt(dayOption);
for (SalesData item : array) {
if (item.day == chosenDay) {
// ...
}
}
Upvotes: 3