2016-03-02 90 views
1

一组数字,我正在寻找一种方法来存储一组数字,在java中商店在Java中

当我生成一个新的号码,我如果这个数字存在于集或不看。

我曾经宣称​​这样的:

HashSet<Integer> tempSet; 
tempSet = new HashSet<Integer>(); 

,但它不工作时,我测试是这样的:

int randomNumber = rand.nextInt(10); 
while (tempSet.contains(randomNumber)) 
{ 
    randomNumber = rand.nextInt(10); 
    System.out.println("randomNumber= " + randomNumber); 
} 

这意味着,如果产生,并在集中存在已数,使用HashSet的成员函数contains进行测试不起作用

这里是完整的代码:

package ex1; 

    import java.util.ArrayList; 
    import java.util.HashSet; 
    import java.util.List; 
    import java.util.Random; 

    public class Main { 

    public static void main(String[] args) { 

     //1- create 10 courses 
      Course[] courseLists = new Course[10]; 

      for(int i=0; i<10; i++){ 
       //create 
       Course course = new Course("course"+i, "courseId"+i, "", 60.0f, 0, 0.0f); 
       courseLists[i]=course; 
      } 

     //2- create 7 professors 
      Professor[] professorLists = new Professor[7]; 

      Random rand= new Random(); 

      int min=1; 

      int max = 6; 

      for(int i=0; i<7; i++){ 
        //create 
        Professor professor = new Professor 
            (
             "ProfessorFirstName"+i, "ProfessorLastName"+i, 
             35, "MALE", "adress"+i, "professorId"+i 
            ); 

        courseLists[i].setAssignedProfessor("profId"+i); 

        professor.setCourseList(courseLists[i]); 

        professorLists[i] = professor; 
      } 

      rand= new Random(); 
      int randomNum1 = rand.nextInt((max - min) + 1) + min; 
      int randomNum2 = rand.nextInt((max - min) + 1) + min; 

      while (randomNum2 == randomNum1) { 
       randomNum2 = rand.nextInt((max - min) + 1) + min; 
      } 

      courseLists[8].setAssignedProfessor("profId"+randomNum1); 
      professorLists[randomNum1].setCourseList(courseLists[8]); 

      courseLists[9].setAssignedProfessor("profId"+randomNum2); 
      professorLists[randomNum2].setCourseList(courseLists[9]); 

      courseLists[7].setAssignedProfessor("profId"+1); 
      professorLists[1].setCourseList(courseLists[7]); 

      //3- create 30 students 
      Student[] studentsLists = new Student[30]; 

      //-------------------- 
      boolean genderValue; 

      //generate number of courses per student 
      //randomNbrCourses: number of courses taken by the current student 
      for(int i=0; i<30; i++){ 
       int minNbrCourses = 1;  
       int maxNbrCourses = 6;  
       int randomNbrCourses; 
       rand= new Random(); 
       randomNbrCourses = rand.nextInt 
            (
            (maxNbrCourses - minNbrCourses) + 1 
           ) + minNbrCourses; 

       //generate random age 
       int minStudentAge=18;  
       int maxStudentAge = 48;  
       int randomAge = -1; 
       rand= new Random(); 
       randomAge = rand.nextInt 
         (
         (maxStudentAge - minStudentAge) + 1 
         ) + minStudentAge; 

       //gender 
       genderValue = Math.random() < 0.5; 
       String gender; 
       if (genderValue == false) 
        gender = "FEMALE"; 
       else 
        gender = "MALE"; 
       //****************************Here I have the HashSet *********// 
       HashSet<Integer> tempSet; 
       tempSet = new HashSet<Integer>(); 
       //****************************************************************// 
       GradeBook gradeBook = new GradeBook(); 

       for (int nbrCourse=0; nbrCourse<randomNbrCourses; nbrCourse++) { 

         Tuple tupleValue = new Tuple(); 

         //generate one number , this number correspand to a course id... 

         //** Here I have to test if a new number exist in the set or not **// 
         int randomNumber = rand.nextInt(10); 
         while (tempSet.contains(randomNumber)) 
         { 
          randomNumber = rand.nextInt(10); 
          System.out.println("randomNumber= " + randomNumber); 
         } 
         //*************************************************// 

         courseLists[randomNumber].setNbrEnrolledStudent(1); 

         float minMark=0.0f; 
         float maxMark=100.0f;  
         Random newRand= new Random(); 

         //generate four random marks for the course.... 
         float randomMark1 = newRand.nextFloat()*(100.0f-0.0f) + 0.0f; 
         tupleValue.setMarkExam1(randomMark1); 

         float randomMark2 = newRand.nextFloat()*(100.0f-0.0f) + 0.0f; 
         tupleValue.setMarkExam2(randomMark2); 

         float randomMark3 = newRand.nextFloat()*(100.0f-0.0f) + 0.0f; 
         tupleValue.setMarkExam3(randomMark3); 

         float randomMark4 = newRand.nextFloat()*(100.0f-0.0f) + 0.0f; 
         tupleValue.setMarkExam4(randomMark4); 

         tupleValue.setFinalMark 
         (
          (randomMark1+randomMark2+randomMark3+randomMark4)/4 
         ); 

         tupleValue.setCourseName("course"+randomNumber); 

         tupleValue.setCourseId("courseId"+randomNumber); 

         gradeBook.setCourseLists(tupleValue); 

        } 

       Student student = new Student 
           (
            "firstName_student"+i,"lastName_student"+i, 
            randomAge, gender, "adress"+i, "idStudent"+i, gradeBook 
           ); 
       studentsLists[i]=student; 

       studentsLists[i].setNbrCourses(randomNbrCourses); 
      } 

      //we have to verify that there is no course with less than 3 student enrolled 

      //print the list of courses 
      getWholeCouces(courseLists, studentsLists); 

      //print the professors and there assigned courses 
      getProfessorsAndAssignedCouces(professorLists); 

      //print the list of all students and the courses enrolled in 
      getStudentsWithEnrolledCourses(studentsLists); 

    } 
    /* 
    static float getMinMarkCourse(){ 

    } 

    static float getMaxMarkCourse(){ 

    } 

    static float getGroupMarkCourse(){ 

    }*/ 

    //method to print the list of all students and the courses they are enrolled in 
    static void getStudentsWithEnrolledCourses(Student[] student){ 
     System.out.println(" "); 
     System.out.println("----------------------------------------------------------"); 
     System.out.println("list of all students and the courses they are enrolled in:"); 
     System.out.println("----------------------------------------------------------"); 
     for (int i=0; i<30;i++){ 
      System.out.print(student[i].getLastName()); 
      System.out.print(" "+student[i].getIdentificationNumber()); 

      GradeBook gb = student[i].getGradeBook(); 

      ArrayList<Tuple> tuple = gb.getCourseLists(); 

      for (int L=0; L< tuple.size(); L++) 
      { 
       System.out.println(" "); 
       System.out.print(" "+tuple.get(L).getCourseId()); 
       System.out.print(" "+tuple.get(L).getFinalMark()); 
      } 
      System.out.println(" "); 
      System.out.println(" "); 
     } 



    } 

    //method to get the professors and there assigned courses 
    static void getProfessorsAndAssignedCouces(Professor[] professor){ 
     System.out.println(" "); 
     System.out.println("---------------------------------------"); 
     System.out.println("professors and there assigned courses:"); 
     System.out.println("---------------------------------------"); 
     for(int i=0; i<7; i++){ 
       System.out.println(" "); 
       System.out.print(professor[i].getFirstName()); 

       System.out.print(" "+professor[i].getIdentificationNumber()); 
       System.out.println(" "); 

       System.out.println(" "); 
       List<Course> courseList = professor[i].getCourseList(); 

       for (int k=0; k < courseList.size(); k++){ 
        System.out.print(" "+courseList.get(k).getCourseId()); 
        System.out.print(" "+courseList.get(k).getNbrEnrolledStudent()); 
        System.out.print(" "+courseList.get(k).getAverageCourseMark()); 
        System.out.println(" "); 
       } 
       System.out.println(" "); 
     } 
    } 

    //method to get the list of all courses 
    static void getWholeCouces(Course[] courseList,Student[] studentsList){ 
     System.out.println("----------------"); 
     System.out.println("list of courses:"); 
     System.out.println("----------------"); 
     // maxMark = max mark of the course 
     // minMark = minimum mark of the course 
     float maxMark = Float.MIN_VALUE; 
     float minMark = Float.MAX_VALUE; 

     float allMarks = 0.0f; 
     float nbOfEnrolledStudent=0.0f; 

     for(int i=0; i<10; i++){ 
       //create 
       String courseName = courseList[i].getCourseName(); 

       //look for enrolled student 
       for(int nbStudent=0; nbStudent<30; nbStudent++){ 
        ArrayList<Tuple> temp = 
        studentsList[nbStudent].getGradeBook().getCourseLists(); 
        for (int j=0;j< temp.size();j++){ 
         if (temp.get(j).getCourseName().equals(courseName)){ 
          if (temp.get(j).getFinalMark() > maxMark) 
           maxMark = temp.get(j).getFinalMark(); 

          if (temp.get(j).getFinalMark() < minMark) 
           minMark = temp.get(j).getFinalMark(); 

          allMarks += temp.get(j).getFinalMark(); 
          nbOfEnrolledStudent+=1; 
         } 
        } 
       } 

       courseList[i].setAverageCourseMark((allMarks)/nbOfEnrolledStudent); 

       System.out.print(courseName); 
       System.out.print(" "+courseList[i].getCourseId()); 
       System.out.print(" "+courseList[i].getAssignedProfessor()); 
       System.out.print(" "+courseList[i].getNbrEnrolledStudent()); 
       System.out.print(" "+minMark); 
       System.out.print(" "+maxMark); 
       System.out.print(" "+(allMarks)/nbOfEnrolledStudent); 
       System.out.println(" "); 
     } 
    } 
} 

回答

5

您没有向HashSet添加任何数字,所以当然contains总是返回false。

int randomNumber = rand.nextInt(10); 
while (tempSet.contains(randomNumber)) 
{ 
    randomNumber = rand.nextInt(10); 
    System.out.println("randomNumber= " + randomNumber); 
} 
tempSet.add(randomNumber); // add this 
+0

更好的办法是测试添加的虚假返回值。如果当然tempSet是(基本)类型Set。 – Neijwiert

2

没有必要在这里使用contains方法。 add() set的方法如果元素已经存在于其中,则返回布尔值。

那么,我们就可以做到这一点:

if(!tempSet.add(randomNumber)){ 
//do something as the number is already present 
} 

这将节省我们从编写的元素已经在if块增加了一个else块。

1

趁着类别(组)的...

做如果插入失败,并且集不允许重复mySet.add返回false ...

一个片段如实施例:

Set<Integer> mySet = new HashSet<Integer>(); 
      for (int i = 0; i < 12; i++) { 
       System.out.println(mySet.add(new Random().nextInt(4))); 
      } 
      System.out.println(mySet); 

输出到这可以是:

true 
true 
false 
false 
true 
false 
true 
false 
false 
false 
false 
false 
[0, 1, 2, 3] 
+0

谎言,我得到完全不同的结果 – Neijwiert

+0

曾听说过讽刺吗? – Neijwiert

+0

Bazinga !!我知道了!!! –