忽略字符串中的重复项并打印一次字符串

Ignore duplicate in string and print string once

对于我的作业来说,我必须列出给定日期在给定建筑物中具有 class 的所有课程(只是课程代码),以便 class 的任何部分在给定时间之间。所涉及的每个课程都应该只列出一次,即使它有多个 classes。除了列出一次课程外,我已经完成了所有工作,即使它有几个 classes。如何忽略文件中的重复字符串?

public void potentialDisruptions(String building, String targetDay, int targetStart, int targetEnd){
    UI.printf("\nClasses in %s on %s between %d and %d%n",
               building, targetDay, targetStart, targetEnd);
   UI.println("=================================");


   boolean containsCourse = false;
   try {
      Scanner scan = new Scanner(new File("classdata.txt"));

       while(scan.hasNext()){

       String course = scan.next();  
       String type= scan.next();   
       String day = scan.next();   
       int startTime = scan.nextInt();   
       int endTime = scan.nextInt();   
       String room = scan.next();


        if(room.contains(building)){  
           if(day.contains(targetDay)){
           if(endTime >= targetStart){
           if( startTime<= targetEnd){

           UI.printf("%s%n", course);   
           containsCourse = true;
        }
        }
        }     
       }
      }
      if(!containsCourse){
          UI.println("error");
        }
    }
    catch(IOException e){
       UI.println("File reading failed");
    }
   UI.println("=========================");

}

您可以将课程放在 Set and loop over them since a Set 中始终包含唯一值。

您可以将所有字符串标记放入 Set and check if that token contain in Set 中,然后再继续如下操作:-

// Declration
.... 
Set courseSet = new HashSet();
...

// Check befor you process further 
if(!courseSet.contains(course))
{
...
// Your Code...
...
courseSet.add(course)
}