java - 尝试制作一个基本的实例化示例但无法

标签 java arrays instantiation instance-variables

所以我最近才开始通过 Lynda.com、hackerranks、SoloLearn 和 codeacademy.com 等学习平台编写 Java 代码

我最近开始学习实例变量、实例方法和实例化。遵循古老的“通过实践来学习”的心态,我编写了一个小脚本,该脚本本质上构建了一个 4x4 2D int 数组并将其返回到实例变量中,然后使用实例方法打印实例变量数组。希望我不会对所有这些术语感到困惑。这是我的代码:

package com.company;

public class Main {

    // created an instance variable called "fill" which is a 2D array
    public int[][] fill;

    // Created an instance method called "displayArray()" to print the array matrix upon call
    private void displayArray() {

        for ( int i = 0; i < fill.length; i++) {

            for (int j = 0; j < fill[i].length; j++){
                System.out.print(this.fill[i][j] + " " );
            }
            System.out.println();
        }
    }

    // Main method to assign values to the 2D instance variable "fill"

    public static void main(String[] args) {

        Main array = new Main(); // instantiation to allow use of "displayArray()" and to allow instance variable "fill" to be filled with integer values
        array.fill = new int[4][4]; // Initiating instance variable "fill"

        //Filling in the 2D array which is an instance variable "fill"
        for (int i = 0; i < array.fill.length; i++){

            for (int j = 0; j < array.fill.length; j++){
                if ( i == j) {
                    array[i][j] = array.fill.length;
                } else {
                    array[i][j] = array.fill.length - Math.abs(i-j);
                }
            }
        }

        // Calling an instance method "displayArray()" to print out array values to console
        array.displayArray();
        }
}

但是,我不断收到错误:

Error:(40, 26) java: array required, but com.company.Main found
Error:(44, 26) java: array required, but com.company.Main found

我有点不知道如何解决它。我是否忽略了什么?或者我不能在主类中创建实例变量/方法吗?

最佳答案

您使用了令人困惑的名称,因此您忘记了在对象array(即实际对象)之后附加变量fill(实际上是数组)您的类(class)名称(Main):

试试这个:

if (i == j) {
   array.fill[i][j] = array.fill.length;
} else {       
   array.fill[i][j] = array.fill.length - Math.abs(i - j);
}

关于java - 尝试制作一个基本的实例化示例但无法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38962932/

相关文章:

java - 比较两个键之间的差异不使用CompareTo java

java - 如何从原始数组创建一个新数组,其中所有差异之和最大?

javascript - 获取值列表在数组中存在不止一次

C# 向类型 T 的类数组添加扩展 Append 方法

java - Java中如何实例化抽象类?

javascript - `Cannot instantiate non-constructior` 关闭编译器警告?

jakarta-ee - 关于 Java SE 和 Java EE 的混淆

Java OpenGL 绘制纹理

java - 为面板制作背景图像时遇到问题

c# - 如何在 C# 中一般地实例化泛型类?