简体   繁体   中英

How could I put my private int into the public int

I want scramble an array by using Math.random multiple times but I don't know how to put the random int into scramble and use the random int multiple times.

 public static void scramble(int[] array){ 
  for(int i = 0 ; i < array.length - 1; i++){
     int temp = array[i];
     array[i] = array[random];
     array[random] = temp;}}

public int random (){
  return (int)(Math.random() *9) + 1;}

Output

100 101 102 103 104 105 106 107 108 109 //Default
 101 104 102 105 103 106 108 109 100 107 //Scrambled
  100 101 102 103 104 105 106 107 108 109//Then sorted

Whole Driver

    import java.lang.Math;

public class Driver03{
   public static void main(String[] args){
      int[] array = {100, 101, 102, 103, 104, 105, 106, 107, 108, 109};
      print(array);
      scramble(array);
      print(array);

      print(array);}

   public static void print(int[] array){
      for(int x = 0; x < array.length; x++){
         System.out.print(" " + array[x]);}
      System.out.println("");}

   public static void scramble(int[] array){ 
      int random = random();
      for(int i = 0 ; i < array.length - 1; i++){
         int temp = array[i];
         array[i] = array[random];
         array[random] = temp;}}

   public int random (){
      return (int)(Math.random() *9) + 1;}

}

Firstly, you have to call the random function like that "random()" not just random

try this code:

public static void scramble(int[] array){ 
  int random = random();
  for(int i = 0 ; i < array.length - 1; i++){
     int temp = array[i];
     array[i] = array[random];
     array[random] = temp;}}

public static int random (){
 return (int)(Math.random() *9) + 1;}

Here is an implementation using the Fisher-Yates shuffling algorithm .

  public static void main( String[] args )
  {
    int[] values = new int[] { 100, 101, 102, 103, 104, 105, 106, 107, 108, 109 };
    System.out.println( "Start: " + Arrays.toString( values ) );
    scramble( values );
    System.out.println( "Scrambled: " + Arrays.toString( values ) );
    Arrays.sort( values );
    System.out.println( "Sorted: " + Arrays.toString( values ) );
  }

  public static void scramble( int[] array )
  {
    // Scramble using the Fisher-Yates shuffle.
    Random rnd = new Random();
    for ( int i = 0; i < array.length - 1; i++ )
    {
      int random = i + rnd.nextInt( array.length - 1 - i );
      int temp = array[ random ];
      array[ random ] = array[ i ];
      array[ i ] = temp;
    }
  }

It doesn't use Math.random() but an instance of Random instead.

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