我必须按照其中提供的日期对对象列表进行排序。我最初的想法是使用开关盒。但这意味着最多31个案例。 这是我使用的代码:
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;
最多可达31例.. 我的问题是......有更简单的方法吗?什么是最有效的方法呢?
谢谢:)
答案 0 :(得分:3)
你只需要一个循环:
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) {
// ...
}
}