【问题标题】:How to return an array如何返回一个数组
【发布时间】:2023-03-06 23:44:01
【问题描述】:

过去几个小时我一直遇到问题……我无法在任何地方找到答案,所以希望有人能在这里帮助我。

我不完全明白我应该如何创建一个数组方法,该方法从方法中选择随机数,然后将它们显示在主方法中。

我遇到的主要问题是如何使用随机 10 个变量来转移方法,以便在 main 方法中替换数组,以便我可以通过 main 方法显示它们?

如果需要任何进一步的信息,请告诉我……非常感谢任何帮助。

以下只是我尝试过的随机组合,但不起作用……我似乎无法让方法数组编译并转移到主方法。

import java.util.ArrayList;
public class oneDimensionArraysNew {
public static void main (String [] args) {

    //Declare and create array    
    int[] aVariable =  new int[10];

    randomValues (aVariable);

    System.out.print("Your random variables are" + aVariable);
  }

    public static double randomValues (int random1 []) {
   int[] randomSet = new int[10];

    for (int i = 0; i < randomSet.length; i++) {
        randomSet[i] = (int) Math.random() * 100;//teacher did not specify max
        return randomSet;

【问题讨论】:

  • 你在做一个 int[] 为什么返回 double[]?:S
  • 您也不要使用 random1 参数。这是故意的吗?
  • 我完全忘记改变它了……过了这么久我什至没有注意到它……虽然现在的问题是要获得回报?

标签: java arrays methods random


【解决方案1】:

要么通过在方法randomValues 中创建一个新数组来返回一个新数组(在这种情况下你必须调整返回类型),或者你填充你通过参数传入的数组并且什么都不返回。

【讨论】:

  • 抱歉,您错过了什么? :-D
  • 他将一个数组作为参数,创建另一个数组并返回它.. 只是在查看返回类型。
【解决方案2】:

您需要发回数组。关注这个sn-p

public static void main (String [] args) {

  //Declare and create array    
  int[] aVariable =  new int[10];
  int[] updatedaVariable = new int[10];

  updatedaVariable = randomValues (aVariable);
  System.out.print("Your random variables are ");

  for(int i : updatedaVariable)
  {
      System.out.print(i + " ");
  }
}

public static int[] randomValues (int random1 []) {
  int[] randomSet = new int[10];

  for (int i = 0; i < randomSet.length; i++) {
      randomSet[i] = (int) (Math.random() * 100);//teacher did not specify max
  }
  return randomSet;
}

【讨论】:

  • 当我编译和运行程序时返回一些数字、字母和字符(例如:[I@393e6226)你知道它是否与 math.random 有关吗?
  • 因为你正在打印数组,提取数字并打印出来!
  • 这个方法返回 0,0,0,0,0… 没有任何变量改变
  • 这是因为您在复制之前将 double 类型转换为 int 。使用(int) (Math.random() * 100)
  • 这个效果最好!只是想从其他人的答案中询问是否将两个数组都保留为主要方法和第二种方法是否明智?我打算再添加大约 7 种方法来使用随机数执行不同的功能?
【解决方案3】:

只需将随机数数组的大小指定为方法的参数,而不是像现在这样传递数组。另外,如果要返回数组,请返回 double[] 而不是单个 double

    public static double[] randomValues (int length) {
    int[] randomSet = new int[10];

    for (int i = 0; i < length; i++) {
        randomSet[i] = (int) Math.random() * 100;//teacher did not specify max
    }
    return randomSet;
    }

【讨论】:

  • 您缺少右括号
【解决方案4】:

换行:

public static double randomValues (int random1 [])

public static int[] randomValues (int random1 []) 
or
public static double[] randomValues (int random1 []) {

【讨论】:

    猜你喜欢
    • 2013-03-04
    • 2013-07-04
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 2014-11-22
    相关资源
    最近更新 更多