samedi 18 février 2017

Check two returned values from an Array in an if statement

My array contains random numbers, the following method succesfully returns the two largest values of it:

 int[] a = {a1 = (int) ((Math.random() * 10) + 1), a2 = (int) ((Math.random() * 10) + 1), a3 = (int) ((Math.random() * 10) + 1)};

public static int[] showtwolargestints(int a[]) {   // returns two largest integers of my array
int largestA = Integer.MIN_VALUE, largestB = Integer.MIN_VALUE;
for(int value : a) {
  if(value > largestA) {
    largestB = largestA;
    largestA = value;
  } else if (value > largestB) {
    largestB = value;
  }
}
return new int[] { largestA, largestB };

}

What I want to do now, is after pushing a button in my GUI, I want to show up certain labels/pictures, depending on what my two largest integers are. Since I am a beginner I do not really know a good method to compare them: This is my code in the GUI class / JButton method:

public void buttonmethod() {   
try {                         
  if (Arrays.toString(myobject.showtwolargestints(myobject.a)).equals("[10, 10]")) {
    label1.setVisible(true);
    Icon i1 = new ImageIcon("pics/ten.png");
    label1.setIcon(i6);

    label2.setVisible(true);
    Icon i2 = new ImageIcon("pics/ten.png");
    label2.setIcon(i7);
  } // end of if
  else if (Arrays.toString(myobject.showtwolargestints(myobjects.a)).equals("[10, 9]")) {
     label1.setVisible(true); // and so on...

I do get results, however they dont seem to work properly since every few starts of my programm, after pushing my Button, it either shows only one label, or no change at all :l

Aucun commentaire:

Enregistrer un commentaire