在Java

时间:2016-03-02 13:47:19

标签: java hashset

我正在寻找一种在java中存储一组数字的方法

当我生成一个新号码时,我必须查看该号码中是否存在该号码。

我使用了这样声明的Hashset

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("  ");
        }
    }
}

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

此处无需使用contains方法。如果元素已经存在于其中,则add() set方法返回布尔值。

所以,我们可以这样做:

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

这将使我们免于编写else块,因为该元素已在if块中添加。

答案 2 :(得分: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]