我正在尝试将二进制文件中的数据读入二维数组,同时整理出最大数据点(在 int[] 中)之上的任何负数或值。我可以让数组在没有异常的情况下正确填充,但是对于超出可接受范围的数据抛出异常是必需的。当我添加异常时,数组永远不会超过第一行。任何见解将不胜感激。
public class DataExceedsMaxDataPoint extends Exception {
public DataExceedsMaxDataPoint() {
super("Error: Data Exceeds Maximum Data Point");
}
public DataExceedsMaxDataPoint(int number, int maxData) {
super("Error: Data(" + number + ") Exceeds Maximum Data Point(" +
maxData + ")");
}
}
public class NegativeData extends Exception {
public NegativeData() {
super("Error: NegativeData Not Allowed");
}
public NegativeData(int number) {
super("Error: Negative Data(" + number + ") Not Allowed");
}
}
import java.io.*;
public class ChemExpDataValidation2 {
public static void main(String[] args) throws IOException {
int[] dataMax = {35, 55, 72, 75, 45, 100}; //max data points
int[][] chemData = new int[6][10];
int number;
int maxData;
boolean endOfFile = false;
FileInputStream fstream = new FileInputStream("data.dat");
DataInputStream inputFile = new DataInputStream(fstream);
System.out.println("Reading numbers from the file:");
while (!endOfFile) {
try {
for (int row = 0; row < 6; row++) {
maxData = dataMax[row];
for (int col = 0; col < 10; col++) {
number = inputFile.readInt();
if (number <= maxData && number > 0) {
chemData[row][col] = number;
}
if (number > maxData) {
throw new DataExceedsMaxDataPoint(number, maxData);
}
if (number < 0) {
throw new NegativeData(number);
}
}
}
for (int row = 0; row < 6; row++) {
for (int col = 0; col < 10; col++) {
System.out.printf("%4d", chemData[row][col]);
}
System.out.printf("\n");
}
} catch (DataExceedsMaxDataPoint e) {
System.out.println(e.getMessage());
continue;
} catch (NegativeData e) {
System.out.println(e.getMessage());
continue;
} catch (EOFException e) {
endOfFile = true;
}
}
inputFile.close();
System.out.println("\nDone.");
}
}