0

Pretty much for my assignment I have to List all the courses (just the course code) that have classes in a given building on a given day such that any part of the class is between the given times. Each course involved should only be listed once, even if it has several classes. I have done everything except listing the course once, even if it has several classes. How do I ignore duplicate strings from a file?

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("=========================");
}
asked Apr 28, 2015 at 11:32
3
  • 2
    Add them all to a collection that doesn't allow duplicates and print all the elements in there. Commented Apr 28, 2015 at 11:33
  • Use HashSet to avoid duplicates elements Commented Apr 28, 2015 at 11:34
  • can you pls explain? I got an error saying no suitable constructor. Sorry, im new at this. @singhakash Commented Apr 28, 2015 at 11:45

2 Answers 2

1

You can put all the string token in Set and check if that token contain in Set befor you process further as below :-

// Declration
.... 
Set courseSet = new HashSet();
...
// Check befor you process further 
if(!courseSet.contains(course))
{
...
// Your Code...
...
courseSet.add(course)
}
answered Apr 28, 2015 at 11:47

1 Comment

I have tried to do that, if(!courseSet.contains(course)){ courseSet.add(course); UI.printf("%s%n", course); containsCourse = true; } but it does not work, it still displays duplicates.
0

You could put the courses in a Set and loop over them since a Set always contains unique values.

answered Apr 28, 2015 at 11:34

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.