java - 我正在尝试在 java 中打印一个数组,我需要使用 public void intArray() 作为方法

标签 java arrays

我需要在仍然使用 String[] 和 public void intArray 的同时打印值

我尝试过移动东西并使用 set 和 get 方法,但它们不起作用

public void intArray()
  {
    //create an int array called num that will store 4 elements
    int[] num = {32,26,19,40};
    //assign 32 to index 0  
    //assign 26 to index 1 
    //assign 19 to index 2  
    //assign 40 to index 3 
    //change index 3 to 57
    num[3] = 57;
  }
  //write a line of code to print length of array:  Length of array of :  
  public static void main(String[]args)
  {
    System.out.println("The length of the array is " + num.length);
    //write a line of code to print index 3:  Index 3 is :    
    System.out.println("Index three is " + num[3]);
    //create a for loop to loop through and print all elements in the array
    for(int element: num)
    {
      System.out.println(element);
    }
  }

我期望得到打印的内容(数字长度、第三个索引和元素),但它们不打印。我需要使用 intArray() 来存储至少 int[] num = {32,26,19,40};和 num[3] = 57;

最佳答案

我的猜测是您正在尝试实现类似的目标:

public class MainClass {

  public static int[] intArray() {
    //create an int array called num that will store 4 elements
    int[] num = {32,26,19,40};
    //assign 32 to index 0
    //assign 26 to index 1
    //assign 19 to index 2
    //assign 40 to index 3
    //change index 3 to 57
    num[3] = 57;
    return num;
  }
  //write a line of code to print length of array:  Length of array of :
  public static void main(String[]args) {
    int[] num = intArray();

    System.out.println("The length of the array is " + num.length);
    //write a line of code to print index 3:  Index 3 is :
    System.out.println("Index three is " + num[3]);
    //create a for loop to loop through and print all elements in the array
    for(int element: num) {
      System.out.println(element);
    }
  }
}

int[] num 是不可见的,因为它在 intArray() 方法中是本地的。对于从 static void main 调用 intArray()intArray() 要么应该是静态的,要么是 main 或应通过创建 MainClass 的新实例来调用: int[] num = new MainClass().intArray();

关于java - 我正在尝试在 java 中打印一个数组,我需要使用 public void intArray() 作为方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55921421/

相关文章:

java - 检测并发修改?

java - 过滤流的日志记录大小

vb.net - 在 .NET 中将结构转换为字节数组

c++ - Arduino 数组没有命名类型

javascript - 选择包含对象的数组对象

java - 升级React Native 0.61.5:Android停留在初始屏幕上

java - Android 编辑文本 : Attempt to invoke interface method on a null object reference

Java 运行 linux(raspbian) 命令(omxplayer) 并获得输出

c - 为什么 'c[&i]' 编译而 'c[i]' 不编译?

c - 如何在 C 中传递可变大小的多维数组?