这是一个学校项目。它将数组中的信息显示为管状格式,每行和每列的总计位于右侧和底部。它会计算除一行之外的所有总计。我找不到问题出在哪里。有人可以帮忙吗?!
import java.util.Scanner;
//program uses class Scanner
public class Ex6_20
{
//method begins java application
public static void main(String[] args)
{
//create Scanner to obtain imput
Scanner input = new Scanner(System.in);
int monthySales=0; //varible to hold mothly sales
int productNum; //varible to hold product number
int salesNum=0; //varible to hold saleperson number
int totalSales=0; //varible to hold total sales
int []totalProduct = {0,0,0,0,0};//build array to hold total product
int []salesTotal = {0,0,0,0,0};//build array to hold total salesperson
// Build array to hold sales information by salesperson and poduct
int[][]sales = {{2000,1500,500,800,0},
{500,2200,600,1000,0},
{1000,2000,300,2100,0},
{2500,4000,400,3000,0},
{300,3200,500,2300,0},
{0,0,0,0}};
//figure total by product
for(int row =0; row < sales.length; row++)
{
for(int column = 0; column < sales[row].length; column++)
totalProduct[column] += sales[row][column];
}//end for
//figure total by salesperson
for(int column = 0; column < sales.length; column++)
{
for(int row = 0; row < sales[column].length; row++)
salesTotal[row] += sales[column][row];
}//end for
//fill totals for product
for(int i = 0; i < 5; i++)
{
sales[i][4] = totalProduct[i];
}//end for
//fill totals for salesperson
for(int i = 0; i < 4; i++)
{
sales[5][i] = salesTotal[i];
}//end for
// print info from array in table format
for(int row =0; row < sales.length; row++)
{
for(int column = 0; column < sales[row].length; column++)
System.out.print(sales[row][column]+"\t");
System.out.println();
}//end for
} //end main method
} //end class
最佳答案
有几个问题:
如果您交换“销售人员的数字总计”中的变量名称“行”和“列”,您会发现您实际上正在执行与“按产品计算的数字总计”完全相同的计算,只是变量名称具有误导性。 (您使用列作为行索引,反之亦然。)到目前为止,totalProduct 和 salesTotal 都包含相同的值,这是不正确的。
这是主要问题。
此外,当您显示销售总额和产品总额时,它们实际上是交换的。我怀疑这是因为您的意思是每行有一个总产品,其中totalProduct[row] += ...,每列有一个总销售额,其销售额为salesTotal[column] += ...,但也许名称只是交换了,行/列索引没问题。
我实际上建议从销售数组中删除额外的总和字段,以便所有行都具有相同的列数,并首先使用硬编码数组边界,以便在获得正确的总和之前使发生的情况更加明显。然后,一旦总和正确,您就可以返回并使其更普遍地发挥作用。否则,您可能会不断收到 ArrayIndexOutOfBounds 异常,而没有明显的原因,这就是我怀疑您迄今为止最终得到此解决方案的原因。
例如,您可以从像这样非常简单的事情开始,然后返回并使其变得更好、更通用,以便它可以处理不同的数组大小:
int[][] table = { { 1, 2, 3, 4, 5 }, { 2, 3, 4, 5, 6 }, { 3, 4, 5, 6, 7 } };
int[] rowSums = new int[3];
int[] colSums = new int[5];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
rowSums[i] += table[i][j];
colSums[j] += table[i][j];
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(table[i][j]);
System.out.print('\t');
}
System.out.println(rowSums[i]);
}
for (int j = 0; j < 5; j++) {
System.out.print(colSums[j]);
System.out.print('\t');
}
System.out.println();
关于Java:二维数组总计未完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35517920/