【发布时间】:2015-10-22 06:32:25
【问题描述】:
我正在尝试将二维数组放入二维列表中。我正在构建一个谷歌 protobuf。我不知道为什么我会抛出异常。我在堆栈上尝试了多个建议,但没有一个能够提供帮助。
这是我的客户端代码:
public class google_cl extends Thread {
static Array createArray() throws IOException{
Array.Builder array = Array.newBuilder();
double[][]arrays = new double[15][15000];
for(int i=1; i< 15; i++){
for(int j=1; j<15000;j++){
arrays[i][j]=Math.random()*100;
}
}
for(int i=1;i<15;i++){
for(int j=1;j<15000;j++){
array = Array.newBuilder().setArrays(i, arrays[1][j]);
}
}
//System.out.println(array);
// Make connection and initialize streams
Socket socket;
try {
socket = new Socket("localhost", 9898);
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
ObjectOutputStream os = new ObjectOutputStream(outputStream);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws IOException {
Average.Builder avger = Average.newBuilder();
//avger.mergeFrom();
try{
avger.mergeFrom(new FileInputStream(args[0]));
}
catch (IOException e) {
System.out.println(args[0] + ": File not found. Creating a new file.");
}
FileOutputStream output = new FileOutputStream(args[0]);// This is where my error occurs.
avger.build().writeTo(output);
output.close();
}
}
这是我的服务器代码:
public class google_sr {
static void average(Average average){
List<Double> list = new ArrayList<Double>();
list = Array.newBuilder().getArraysList();
double max = 0.00;
Double sum = 0.00;
if(!list.isEmpty()) {
for (int i =1; i<15000;i++) {
sum += list.get(i);
}
max= sum.doubleValue() / list.size();
}
Average.Builder avg = Average.newBuilder();
System.out.println(avg.setAverages((int)max));
}
public static void main(String[] args) throws Exception {
google_sr p = new google_sr();
Average averag = Average.parseFrom(new FileInputStream(args[0]));//Where my error occurs
average(averag);
if (args.length != 1) {
System.err.println("Usage Error");
System.exit(-1);
}
}
}
最后,这是我的 proto 文件:
message Array{
repeated double arrays = 1;
}
message Array2{
repeated Array arrays=1;
}
message Average{
optional int32 averages =1;
}
这是我的堆栈跟踪:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at cisc_434_google_protocol.google_cl.main(google_cl.java:82)
【问题讨论】:
-
发布您的堆栈跟踪
-
发布控制台输出,以便问题清晰
-
刚刚做了,@SanjaySinghRawat
-
看起来 try 有一个未捕获的索引越界异常,这就是错误在它之后的原因。我养成的一个好习惯是在对参数进行任何操作之前先检查 args 的长度。
标签: java arrays exception arraylist protocol-buffers