gpt4 book ai didi

java - 如何确保 Java 跨方法找到变量?

转载 作者:行者123 更新时间:2023-12-02 08:08:53 26 4
gpt4 key购买 nike

我正在尝试编写一个 Java 类,其中 main 方法创建一个数组来存储 30 个整数。然后,我在 main 方法中调用一个名为 LOAD() 的方法,该方法的作用是用 1-300 之间的 30 个整数填充数组。

我已经编写了一个完整的 Java 类来执行此操作,但编译器不断告诉我此错误,它无法找到符号 randomThirty 的符号,即我的数组变量的名称。

这是到目前为止我的代码,但我不确定为什么 LOAD() 没有选取我的 randomThirty,也许我需要在 LOAD 的括号中显式传递参数?

import java.util.*;

public class arrayNums
{

public static void main(String args[])
{
//main method which creates an array to store 30 integers

int[] randomThirty = new int[30]; //declare and set the array randomThirty to have 30 elements as int type

System.out.println("Here are 30 random numbers: " + randomThirty);

LOAD(); // the job of this method is to populate this array with 30 integers in the range of 1 through 300.
}


public static void LOAD()
{
// looping through to assign random values from 1 - 300
for (int i = 0; i < randomThirty.length(); i++) {
randomThirty[i] = (int)(Math.random() * 301);
}

最佳答案

线索就在你的评论中:

LOAD(); // the job of this method is to populate this array

因此,您已经有了一个想要该方法使用的数组...您应该将其传递给该方法:

load(randomThirty);

// Method declaration change...
public static void load(int[] arrayToFill)

当方法自然不处于它有权访问状态的上下文中时,这是一个好方法。在这种情况下,这看起来是合适的方法。对于其他情况,您可以根据上下文使用静态变量或实例变量。

(顺便说一句,您应该查看 Random 类 - 并了解 Java 命名约定。)

关于java - 如何确保 Java 跨方法找到变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7743077/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com