Robert
Robert

Reputation: 47

Can I stop my program from printing repetitive information

I am trying to fix up my project to find and tell me which students are trying to register with another name so I programmed my code to search my arraylist and find those with same id number as follows, but is it possible to change or add something so that it does not print out the same information twice
Example test case

Student ID 103 is repeating the class as names Mark Wall and Stacy Gwee
Student ID 103 is repeating the class as names Stacy Gwee and Mark Wall



for(int n = 0; n<studentList.size(); n++)
         {
         for(int m = 0; m<studentList.size(); m++)
            {
            if(studentList.get(n).getId().equals(studentList.get(m).getId()) && !studentList.get(n).getName().equals(studentList.get(m).getName()))
               {
               System.out.println("Student ID " + studentList.get(n).getId() + " is repeating the class as names " + studentList.get(n).getName() + " and " + studentList.get(m).getName());
               }
            }
          }

Upvotes: 0

Views: 100

Answers (4)

shinjw
shinjw

Reputation: 3431

This would be the proper way to do it:

  1. Create a Map
  2. Add your matches to the map
  3. Check the map if the ID has already been used before checking your List

You need some way to flag your duplicates. You can create a list or an array to mark these duplicates. You then would check the ID to make sure that it hasn't been called before.

Upvotes: 1

Morag Hughson
Morag Hughson

Reputation: 7619

If you imagine your array as a grid n spaces wide and m spaces high, you are looking at each grid square.

If you draw a diagonal line across your grid you actually only need to look at those above the line (or below).

Therefore you inner loop could start, not at zero, but at the value of n.

Upvotes: 0

Kuba Spatny
Kuba Spatny

Reputation: 27000

To do it simply change the second for loop:

for(int m = 0; m < n; m++)

Upvotes: 2

Jean Logeart
Jean Logeart

Reputation: 53859

Simple ways:

for(int m = 0 ; m < n ; m++)

Or

for(int m = n + 1 ; m < studentList.size() ; m++)

Upvotes: 4

Related Questions