繁体   English   中英

如何将随机值从一种方法提取到另一种方法?

[英]how do you pull random values from one method into another?

长话短说。 即时通讯应该编写一个具有一维数组的程序,该数组包含10个整数,并使用冒泡排序对数组进行排序。

到目前为止,我已经写了:

System.out.print("The unsorted list is: ");
         int[] numbers = new int[10];       
            //Generates 10 Random Numbers in the range 1 -100
            for(int i = 0; i < numbers.length; i++) {
              numbers[i] = (int)(Math.random() * 100 + 1);
              System.out.print(numbers[i] + " " );
           }//end for loop

但是我不清楚如何将随机值从一种方法传递给另一种方法。 处理器很友好,可以包含一个冒泡排序代码,但是我在主方法中如何从数组中提取随机值一无所知。

Bubblesort代码:

 public static void bubbleSort(int[] list) 
      {
        int temp;

          for (int i = list.length - 1; i > 0; i--) 
          {
             for (int j = 0; j < i; j++) 
             {
               if (list[j] > list[j + 1]) 
               {
               temp = list[j];
               list[j] = list[j + 1];
               list[j + 1] = temp;
               }
             }
          }
       }

非常感谢您提供任何提示或帮助。

功能

public static void bubbleSort(int[] list)

期望int[] list一个整数数组作为参数,因此您传递了一个整数数组。

public static void main(String args[]){
   int[] mList = {12,3,54,67,8,90};
   bubbleSort(mList);
   for(int i = 0 ; i < mList.length ; i++)
      System.out.println(mList[i] + ", ");
}

众所周知,请注意void main(String[] args)也需要一个数组(字符串数组)作为参数。

同样,由于参数int[] list是非基本参数(即,不是普通的int,float,char或它们的包装对象),因此将参数作为参考而非值接收。 因此,对数组所做的任何修改也将反映在main函数中。

像这样使用它:

System.out.print("The unsorted list is: ");
         int[] numbers = new int[10];  
               bubbleSort(numbers);
            //Generates 10 Random Numbers in the range 1 -100
            for(int i = 0; i < numbers.length; i++) {
              numbers[i] = (int)(Math.random() * 100 + 1);
              System.out.print(numbers[i] + " " );
           }//end for loop

 public static void bubbleSort(int[] list) 
      {
        int temp;

          for (int i = list.length - 1; i > 0; i--) 
          {
             for (int j = 0; j < i; j++) 
             {
               if (list[j] > list[j + 1]) 
               {
               temp = list[j];
               list[j] = list[j + 1];
               list[j + 1] = temp;
               }
             }
          }
       }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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