【问题标题】:Filling an array with ints and strings using a class declaration使用类声明用整数和字符串填充数组
【发布时间】:2017-09-19 18:40:01
【问题描述】:

所以我不确定我在根据我最初声明的已建立数组打印数组时缺少什么步骤。我知道 java 有其他方法来打印数组,但我试图让这些步骤更长(而不是使用 Java 快捷方式),因此更容易将相同的方法应用于其他语言。如果有人可以看看我所拥有的并告诉我我缺少什么,我将不胜感激。

更新:我觉得很愚蠢,因为这是一个简单的解决方案,但现在我正在处理另一个问题。我需要数组来接受字符串和整数,所以我创建了一个带有公共类型 word 和 number 的类,但我不确定如何正确填充数组。我知道我没有设置数字来填充数组,但如果有人能帮我找出一个,我可以自己做另一个。

   package employeetotalhours;

 import java.util.ArrayList;

 public class employeetotalhours {  // main class declaration

public static class Table{          // sub class declaration
    public int number;      // establish input field values for ints
    public String word;     // establish input field values for strings
    Object array[];
}

public static void main(String[] args){ // main method  

Table[] table = new Table[9];

Table word = null;

table[0] = word;

ArrayList<Table> Table = new ArrayList<Table>();

Table.add(new Table());

 //         {{"Employee ","Su","M","T","W","T","F","Sa","Total"}, 
 //         {"EmpID 0       ","4 ","2","5","3","4","5","8 ", "0"}, 
 //         {"EmpID 1       ","1 ","7","8","4","3","3","4 ", "0"}, 
 //         {"EmpID 2       ","2 ","3","3","4","3","3","2 ", "0"}, 
 //         {"EmpID 3       ","3 ","3","3","7","3","4","1 ", "0"}, 
 //         {"EmpID 4       ","1 ","3","2","4","3","6","3 ", "0"}, 
 //         {"EmpID 5       ","5 ","3","4","4","6","3","4 ", "0"}, 
 //         {"EmpID 6       ","8 ","3","7","4","8","3","8 ", "0"}, 
 //         {"EmpID 7       ","2 ","6","3","5","9","2","7 ", "0"}};
    // all array data, multiple lines can be used as long as code is not closed with ;

    int rows = 9; // establish array row size

    int columns = 9; // establish array column size

    for(int i = 0; i < rows; i++)
    {
        for(int j = 0; j < columns; j++)
        {
            System.out.print(table[i] + " ");
        }
            System.out.println();
    }
}
}

【问题讨论】:

    标签: java arrays class


    【解决方案1】:

    在打印所有值的循环之前,您有这个循环:

    for(int i = 0; i < rows; i++) // loop to cycle through cells in array table
        for(int j = 0; j < columns; j++)
            array[i][j] = 0;
    

    在此循环中,您将数组的每个元素都设置为 0。
    所以当你打印元素时,一切都是0

    【讨论】:

      【解决方案2】:

      您将所有数组元素写入零,这就是将值重新初始化为 0 的原因。

      for(int i = 0; i < rows; i++) // loop to cycle through cells in array table
          for(int j = 0; j < columns; j++)
              array[i][j] = 0;
      

      【讨论】:

      • 好的,那么我需要删除那个 for 循环吗?
      • 再看一遍我看到了,感觉很笨,有机会我会尝试不循环的
      • @SirPapilonius 不要感到难过,每个人都在做同样的事情:D
      猜你喜欢
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-22
      • 1970-01-01
      • 2019-04-11
      相关资源
      最近更新 更多