简体   繁体   中英

How do I keep the Reversed method from affecting the Squared output?

public static void Reversed (int[] array){
  for (int i = 0; i < array.length / 2; i++){
     int temp = array[i];
     array[i] = array[array.length - (1 + i)];
     array[array.length - (1 + i)] = temp;
  }
}
public static void Squared (int[] array){
  for (int i = 0; i < array.length; i++){
     array[i] = array[i] * array[i];
  }
}
public static void main (String[] args){
  int[] list = new int[5];
  for (int i = 0; i < list.length; i++)
     list[i] = (int) (Math.random() * 1001);

  System.out.println ("The original set is " + Arrays.toString(list) + ".");
  System.out.println ("\nThe largest number is " + Max(list) + ".");
  System.out.println ("The smallest numer is " + Min(list) + ".");

  Reversed(list);
  System.out.println ("The reversed array is " + Arrays.toString(list) + ".");    

  Squared(list);
  System.out.println ("The array squared is " + Arrays.toString(list) +       
    ".");
  }

The methods work as they are supposed to, but the output reverses the squared numbers too, even though they are not supposed to be reversed. The squared set is supposed to be the same order as the original randomly generated set. I tried putting the Squared method ahead of the Reversed method, but it did not have any affect. Is there a way to make a method "self-contained" of sorts?

Thanks in advance!!!

Okay let me guide you through your own program.

You are creating an array of random number, so far so good. Then you reverse the list by calling Reversed() and the the array is reversed, also fine. In third place you are squaring the the numbers of the array by calling Squared() , which does work as well.

Now think about it, you have reversed the array once, why shouldn't you be able to reverse it again with the same method? Because that is,what method are used for! They do not only keep your code more readable, they also allow you to reuse the same piece of code over and over again.

Regarding this you can call Reversed() a 2nd time before printing your squared array to the screen:

public static void main (String[] args){
    int[] list = new int[5];
    for (int i = 0; i < list.length; i++)
       list[i] = (int) (Math.random() * 1001);

    System.out.println ("The original set is " + Arrays.toString(list) + ".");

    Reversed(list);
    System.out.println ("The reversed array is " + Arrays.toString(list) + ".");    

    Squared(list);
    Reversed( list );
    System.out.println ("The array squared is " + Arrays.toString(list) +       
      ".");
    }

Best regards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM