有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在方法中使用类变量

在java中,如何在方法中使用类变量

这是我的密码

public class ExamQ3a {
    String[] descriptionArr = new String[50];
    static int[] codeArr = new int[50];

    public static void displayItems(int count, int[] codeArr,
            String[] descriptionArr) {
        count = this.codeArr.length;
        for (int i = codeArr.length; i < codeArr.length; i--) {

        }
    }
}

这里突出显示的一行是count=this。科达尔。长我得到的错误是,不能从静态上下文引用非静态变量。但我已经把变量设为静态。那又有什么好处呢

所以只能按要求!我不是想问整个问题,只是想知道为什么我想使用静态,这是一个实践问题

You are to develop a simple application system to manage the inventory in a company. The system should be able to maintain a list of up to 50 items. Each item has a unique integer code and a description.

(a) Write Java statements that declare and create two arrays to store the code and the description of the items.

(b) Write Java method with the following method signature:

public static void displayItems(int count, int[] codeArr, String[] descriptionArr)

This method displays the code and description of all items in the company in tabular form with appropriate column heading.

Parameters: codeArr: the array that stores the codes of the items

descriptionArr: the array that stores the descriptions of the items

count: the number of items in the system


共 (2) 个答案

  1. # 1 楼答案

    另一点需要注意的是,在下面的代码中,语句1将永远不会执行:

    for (int i = codeArr.length; i < codeArr.length; i ) { statement1; }
    

    应该是

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

    或者

    int length = codeArr.length;
    for (int i = (length-1); i > -1 ; i ) { ... }
    
  2. # 2 楼答案

    静态世界中没有this。摆脱它。解释一下,this指的是当前的实例,当处理静态方法或变量时,处理的是与类关联的项,而不是任何一个特定实例。因此,将代码更改为:

    count = codeArr.length;
    

    编辑1
    顺便说一句,你不想像} } }这样把结束括号捆起来,这会让你的代码很难阅读和理解。空白是免费的,所以最好明智地使用它来提高代码的可读性

    编辑2
    你说:

    so how would I reference the array codeArr to the class variable codeArr?

    您位于类内部,这里不需要使用类变量名,因为假定使用了它。只要使用静态变量或方法名,您就应该是金色的

    编辑3
    对这种类型的变量使用static会给代码带来不好的味道。我认为如果这是一个实例变量而不是一个静态变量,你的整个程序会更好。有关这方面的更多讨论,您可以告诉我们为什么决定将变量设为静态