java - 在 Java 中存储一组数字

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

最佳答案

您没有向 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

关于java - 在 Java 中存储一组数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35749014/

相关文章:

java - EntityNotFoundException - Spring mvc 无法查询具有抽象类属性的对象,但可以查询属性对象。并且仅限于某些遗产

java - 如何使用opencv在代理后面捕获视频

java - HashSet addAll 方法修改类内部字段

c# - 现有元素的 HashSet 性能添加与包含

java - Trim() 方法不删除文本前面的空格吗?

java - 我如何才能始终记住每个传感器的最新值并将其写入文件?

java - Java Spring多线程原子性问题

java - 查找 {1,2,3} 幂集的算法

javascript - 在 MainActivity.java React-native Android 中找不到符号

Java HashSet 允许重复