1

I have a problem with a program I'm writing for a school assignment. Essentially, before this piece of code, I already recieve and work with a bunch of information that I store into an array of objects. Now I have to sort this array (after it's sorted, I will have to calculate some things in the order of the PRIORITY variable).

presume I already have a MyClass[] array called input, that stores a finite amount of MyClass objects.

MyClass[] priorityArray = new MyClass[input.length];
for (int i=0; i<priorityArray.length; i++) {
  int maxIndex = 0;
  int maxPrivilege = input[i].returnPrivilege();
  for (int j=1; j<input.legnth; j++) {
    int currentPrivilege = input[j].returnPrivilege();
    if (currentPrivilege > maxPrivilege) {
      maxPrivilege = currentPrivilege;
      maxIndex = j;
    }
  }
  priorityArray[i] = input[maxIndex];
  input[maxIndex].setPrivilege(-900000000);


}

the MyClass class if nothing fancy, but of course, contains a proper constructor, getter and setter methods and an integer variable "privilege".

I'm getting an error in my final tests of the program and, seeing as the program returns privileges as "-900000000", it has to have something to do with this part of the code. It's also not even writing certain MyClass instances from the input array into the priorityArray array.

How can I clead this up? Help.

1 Answer 1

1

I'll rewrite my answer totally.

In this line

priorityArray[i] = input[maxIndex];

You are assigning object from one array to another array by reference. It means that there is only one object and you set value to -9000000 in the next line to it. Of course element in priorityArray will have the same changes. To fix it you need to clone your object here.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm not sure I understand - I want the "j" for loop to go through the entire "input" array each time. so the for loop has to start at 0 (I'm starting at 1, because I assign the value of input[0].returnPrivilege() to the maxPrivilege variable when declaring it. Also, what do you mean by "use a debugger"?
Thank you That solved my problem. Unfortunately, I'm still not 100% done with the project, but the priorities are now showing up correctly. Thanks!

Your Answer

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.