【问题标题】:How could I put my private int into the public int我怎么能把我的私人 int 放入公共 int
【发布时间】:2019-11-08 17:15:26
【问题描述】:

我想通过多次使用 Math.random 来打乱数组,但我不知道如何将随机整数放入打乱中并多次使用随机整数。

 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;}

输出

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

整个驱动程序

    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;}

}

【问题讨论】:

  • 你能解释得更好吗?举例说明您的输入和预期输出也很有用
  • 要注意的一件事是您的 random() 函数返回一个介于 1 和 9 之间的值,如果传递给 scramble() 函数的数组长度不是至少 10 个元素,您可以接收索引超出范围异常。您可能需要更新 random() 函数以接受数组中要加扰的元素数量的参数。

标签: java private public


【解决方案1】:

这是使用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;
    }
  }

它不使用Math.random(),而是使用Random 的实例。

【讨论】:

    【解决方案2】:

    首先,你必须像“random()”那样调用随机函数,而不仅仅是随机的

    试试这个代码:

    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;}
    

    【讨论】:

    • 我确实尝试过,但出现了这个错误“无法从静态上下文引用非静态方法 random()”
    • 将“静态”添加到“随机”:
    • @ChaseDiaz ,我更新了代码。我想这会解决你的问题
    猜你喜欢
    • 2021-06-19
    • 2021-12-22
    • 2015-02-04
    • 2014-11-22
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    相关资源
    最近更新 更多