【发布时间】:2016-04-26 23:35:29
【问题描述】:
我已经上下搜索了解决我的问题的方法,但似乎没有一个有效。一个特定的参考——this 和this,尤其是this。但是,无论我如何实现它们,我都会收到 OutOfBoundsError,我无法理解。
该计划是一门课的额外学分。其实很简单--
程序说明:使用二维数组解决以下问题。一家公司有四个销售人员(1 到 4),他们销售五种不同的产品(1 到 5)。每天一次,每个销售人员都会为销售的每种不同类型的产品提交一张单据。每个单据包含:
销售人员编号
产品编号
该产品当天销售的总美元价值因此,每个销售人员每天会传递 0 到 5 个销售单。假设上个月所有单据的信息都可用。每个数据行包含 3 个数字(销售人员编号、产品编号、销售额)。
编写一个程序,读取上个月销售的所有这些信息,并按销售人员按产品汇总总销售额。
提供的数据:
1 2 121.77
1 4 253.66
1 5 184.22
1 1 97.55
2 1 152.44
2 2 104.53
2 4 189.97
2 5 247.88
3 5 235.87
3 4 301.33
3 3 122.15
3 2 301.00
3 1 97.55
4 1 125.66
4 2 315.88
4 4 200.10
4 3 231.45
只有在尝试计算列时才会出现错误。我的行工作;无论我如何更改 for 循环或数组的行或列中的任何索引,它都不起作用。起初我分别计算了我的行,然后我的列求和,但它也不起作用。我显然忽略了一些我错过的东西。
这是我的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.text.DecimalFormat;
import java.util.Scanner;
public class prog480u {
static Scanner inFile = null;
public static void main(String[] args) {
try {
// create scanner to read file
inFile = new Scanner(new File ("prog480u.dat"));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
System.exit(0);
}
// make the array
int x = 0;
int y = 0;
double[][] profits = new double[4][5];
while (inFile.hasNext()) {
x = inFile.nextInt(); // use sales numbers as coordinates
y = inFile.nextInt();
profits[x - 1][y - 1] = inFile.nextDouble();
}
// check if it's okay
System.out.println("");
double[][] columnProfits = sums(profits);
for (int a = 0; a < columnProfits.length; a++) {
System.out.print((a+1) + "\t");
for (int b = 0; b < columnProfits[a].length; b++) {
System.out.print(columnProfits[a][b] + "\t");
}
System.out.println("");
}
double[] bottomRow = columnSums(columnProfits);
for (int a = 0; a < bottomRow.length; a++) {
System.out.print("Total:" + bottomRow + "\t");
}
}
public static double[][] sums (double[][] q) {
double[][] array = new double[5][6];
array = q;
double sum = 0;
for (int a = 0; a < array.length; a++) {
for (int b = 0; b < array[0].length; b ++) {
sum += array[a][b]; // add everything in the row
}
array[a][4] = sum; // set that row to the last column
sum = 0; // reset sum to 0
}
return array;
}
public static double[] columnSums (double[][]q) {
double[][] array = new double[5][6];
array = q;
double sum2 = 0;
double[] columns = new double [5];
for (int a = 0; a < array.length; a++) {
for (int b = 0; b < array[0].length; b ++) {
sum2 += array[b][a];
columns[b] = sum2;
}
sum2 = 0; // reset sum to 0
}
return columns;
}
}
非常感谢您的宝贵时间。我感觉我的程序快要运行了,但是这个小错误把我推到了边缘。
【问题讨论】:
-
看起来你需要一个'+=',而不是一个'=',当你阅读双打
标签: java arrays multidimensional-array file-io