我有两个数组。一个有一串名字。另一个是一个多维数组,在三列中有一个相关的小时列表,表示每一天。
我试图匹配这两个数组,以便我可以显示具有正确总薪水的名称。但是,我怀疑输入没有插入到小时[x] [y]的数组中。因此,没有存储,我不能再显示总数。
public class NameList
{
public static void main(String[] args)
{
String[] name = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
int[][] hour = new int[10][3];
String input;
Integer x = null, y = null, z, total = 0, pay= 0;
boolean cancel = false;
for (int index = 0; index < name.length; index++) // First array - String names.
{
for (x = 0; x <= hour.length; x++) // Second array - name name row.
{
for (y = 0; y < hour[x].length; y++) // Second array - name working hours column.
{
z = y + 1;
input = JOptionPane.showInputDialog("Please enter " + name[index] + "’s day " + z + " hours: " );
pay = Integer.parseInt(input);
hour[x][y] = pay;
total += hour[x][y];
}
JOptionPane.showMessageDialog(null, name[index] + " total sum of hours is: " + total);
total = 0;
break;
}
}
cancel = true;
}
}
答案 0 :(得分:0)
我怀疑问题是你已经嵌套了三个for循环,当我相信你应该只需要2.因为名字数组和小时数组可能是对齐的,所以名字[3]是&# 34; d&#34;而[3] [天]是工作者D在某一天工作的小时数,你应该只需要总共两个for循环,一个将作为数组名称和小时的第一个维度的索引,并且第二个指数当天。
此外,您可以在语句中声明变量,即
for(int index = 0 ; index < name.length ; index++)
编辑:我看到你在程序中使用了这个确切的行...是否有任何理由说明你没有为其他两个循环使用这种语法?
答案 1 :(得分:0)
你有3个for循环,因为break
你只需要几小时替换第一行的值。删除x的内部for循环。
String[] name = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
int[][] hour = new int[10][3];
String input;
Integer y = null, z, total = 0, pay= 0;
boolean cancel = false;
for (int index = 0; index < name.length; index++) // First array - String names.
{
for (y = 0; y < hour[index].length; y++) // Second array - name working hours column.
{
z = y + 1;
input = JOptionPane.showInputDialog("Please enter " + name[index] + "’s day " + z + " hours: " );
pay = Integer.parseInt(input);
hour[index][y] = pay;
total += hour[index][y];
}
JOptionPane.showMessageDialog(null, name[index] + " total sum of hours is: " + total);
total = 0;
}
/*for (int x = 0; x < hour.length; x++) {
System.out.println(name[x] + " : " + Arrays.toString(hour[x]));
}*/
cancel = true;