2016-05-20 1 views
0

Как получить доступ ко всем значениям или массивам вне цикла? Я хочу получить доступ к нему за пределами цикла, потому что мне нужно сгруппировать их в соответствии с availableID. Я попытался сгруппировать их внутри цикла, то результат будет не так, что я ожидал ..получить доступ ко всему значению массива вне цикла и сгруппировать его

Ожидаемый результат:

Student Name Project Title Supervisor Name Examiner Name Start End Date 
2013438096   Hello    1025   1003  7  7 null 
2013339255   Hello    1024   1001  7  7 null 

Student Name Project Title Supervisor Name Examiner Name Start End Date 
2013366609  Hello     1027   1013   2  2 null 
2011679914  Hello     1015   1014   2  2 null 
2013765397  Hello     1026   1014   2  2 null 

Тем не менее, оказывается, как это:

Student Name Project Title Supervisor Name Examiner Name Start End Date 
2013339255  Hello    1024   1001   7  7 null 



Student Name Project Title Supervisor Name Examiner Name Start End Date 
2013438096  Hello    1025   1003   7  7 null 



Student Name Project Title Supervisor Name Examiner Name Start End Date 
2013765397   Hello    1026   1014   2 2 null 



Student Name Project Title Supervisor Name Examiner Name Start End Date 
2011679914   Hello    1015   1014   2 2 null 



Student Name Project Title Supervisor Name Examiner Name Start End Date 
2013366609   Hello    1027   1013   2 2 null 

я понял, я должен сгруппировать их вне цикла, так что это моя логика:

try{ 
      String studentName = null; 
      String projectTitle = null; 
      String SVName = null; 
      String EXName = null; 
      int availID = 0; 
      String day = null; 
      Time start = null; 
      Time end = null; 
      Date date = null; 

      for (int i=0 ; i<studentID.length ; i++){ 

       List<Object[]> list = (List<Object[]>) GenerateScheduleDAO.getFree(supervisorID[i],examinerID[i],studentID[i]); 

       Object[] array = null; 

       if(!list.isEmpty()){ 

       //declaring the variables 
        studentName = (String) array[7]; 
        ....... // all variables 
        date = (Date) array[3]; 

       }//check list is NOT empty 
       else if (list.isEmpty()){ 

        list = (List<Object[]>) GenerateScheduleDAO.getOtherFree(examinerID[i], supervisorID[i],studentID[i]); 


        //declaring the variables 
        studentName = (String) array[7]; 
        ....... // all variables 
        date = (Date) array[3];     

       } 

    }//student loop 

      if (availID == 2) { 
        out.println("<br><center><table id=\"t01\"><tr>" 
          + "<th>7Student Name</th>" 
          + "<th>Project Title</th>" 
          + "<th>Supervisor Name</th>" 
          + "<th>Examiner Name</th>" 
          + "<th>Day</th>" 
          + "<th>Start</th>" 
          + "<th>End</th>" 
          + "<th>Date</th>" 
          + "</tr>"); 
        out.println("<tr>"); 
        out.println("<td>"+ studentName+"</td>"); 
        out.println("<td>"+ projectTitle +"</td>"); 
        out.println("<td>"+ SVName +"</td>"); 
        out.println("<td>"+ EXName +"</td>"); 
        out.println("<td>"+ day +"</td>"); 
        out.println("<td>"+ start +"</td>"); 
        out.println("<td>"+ end+"</td>"); 
        out.println("<td>"+ date+"</td>"); 
        out.println("</tr>"); 
        out.println("</center></table><br><br>"); 
      }//2 
     else if (availID == 7) { 
        //Table consist of same attribute as above 
       }//7 
       if (availID == 10) { 
        //Table consist of same attribute as above 
       }//10 
       if (availID == 16) { 
        //Table consist of same attribute as above 
       }//16 
       else if (availID != 2 && availID != 7 && availID != 10 && availID == 16) { 
        //Table consist of same attribute as above 
        }//else 

}// first try 

этот код может восстановить только Ла st значение массива. Но я хотел бы получить доступ ко всем данным массива. Как я могу это решить? ИЛИ мне нужно каждый раз встраивать петлю в каждое условие?

+0

Как я писал ответ, я понял, у вас есть некоторые проблемы с кодом. Вы уверены, что ваш код работает без исключения? Вы не устанавливаете переменную 'Object [] array', но позже получаете доступ к ней. – Underbalanced

+0

@ Недостаточно, конечно, исключение. Честно говоря, я урезал много своих кодов, поэтому он не будет слишком длинным. Люди не хотят читать его :(Если вы не попросите об этом, я выложу длинный номер – user6308605

+0

, что он представляет, и где вы задаете? Я вижу, что вы инициализируетесь с 0, но не устанавливаете его. – Vijay

ответ

0

Возможно, с вашей настройкой может возникнуть трудность. Я переписал то, что вы пытаетесь, а также сгруппировал все, используя availId. Я набрал все это в блокноте, поэтому, пожалуйста, извините любые {} проблемы.

Comparator

Comparing Ints

public class StudentExam { 

      String studentName = null; 
      String projectTitle = null; 
      String SVName = null; 
      String EXName = null; 
      int availID = 0; 
      String day = null; 
      Time start = null; 
      Time end = null; 
      Date date = null; 

    public StudentExam(Object[] studentExamArray){ 
     this.studentName = studentExamArray[7]; 
     this.projectTitle = studentExamArray[]; //TODO Insert index 
     this.SVName = studentExamArray[]; //TODO Insert index 
     this.EXName = studentExamArray[]; //TODO Insert index 
     this.availID = studentExamArray[]; //TODO Insert index 
     this.day = studentExamArray[]; //TODO Insert index 
     this.start = studentExamArray[]; //TODO Insert index 
     this.end = studentExamArray[]; //TODO Insert index 
     this.date = studentExamArray[3]; //TODO Insert index 
    } 
} 


public static void main(String[] args){ 

    List<Object[]> list; 

    try{ 
     List<Object[]> list = (List<Object[]>)GenerateScheduleDAO.getFree(supervisorID[i],examinerID[i],studentID[i]); 
    } catch (Exception e){ 
     e.printstacktrace(); 
     // Do something ? 
    } 

    if(list == null || list.size() == 0){ 
     return; // Or throw exception 
    } 


    List<StudentExam> studentExams = new ArrayList(); // here you can change the list implimentation and use to make a sorted list using a comparator or we can sort it later 
    for(Object[] studenExamArray : list){ 
     StudenExam studentExam = new StudentExam(studenExamArray); 
     studentExams.add(studentExam); 
    } 


    // Now that you have parsed your data you can go ahead and sort it, and print it the way you want... 
    Collections.sort(list, new Comparator() { 
       @Override 
       public int compare(StudentExam se1, StudentExam se2) { 
        return Integer.compare(se1.availID, se2.availID) 
       } 
      }); 


    for(StudentExam studenExam : studentExams){ 
     switch(studentExam.availID){ 
      case 0:{ 
       // Do stuff 
       break; 
      } 
      case 0:{ 
       // Do stuff 
       break; 
      } 
      case 0:{ 
       // Do stuff 
       break; 
      } 
      case 0:{ 
       // Do stuff 
       break; 
      } 
      case 0:{ 
       // Do stuff 
       break; 
      } 
     } 
    } 
} 
+0

Я действительно не понимаю это tbh – user6308605

+0

В основном я принимал и создавал класс 'StudentExam', чтобы помочь устранить основной метод. Здесь вы создаете структуру данных, а затем просто сортируете их. Ваш код отсутствовал, поэтому мне пришлось поставить // TODO. Пример, который я опубликовал, очень простой, не знаю, как еще помочь. – Underbalanced

+0

Есть ли другой способ, которым я могу обойтись без использования 'Collections.sort'? – user6308605

Смежные вопросы