java - 如何从 .csv 列获取最小值和最大值

标签 java

我尝试从 .csv 文件获取最小值和最大值,但我的代码抛出此错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 0 at PSAnalyserGui.Test.main(Test.java:53)

代码:

public class Test {

 public static class ColMapper extends
   Mapper<Object, Text, Text, DoubleWritable> {
  public void map(Object key, Text value, Context context)
    throws IOException, InterruptedException {
   String[] cols = value.toString().split(",");
   for (int i = 0; i < cols.length; i++) { 
    context.write(new Text(String.valueOf(i + 1)),new 
DoubleWritable(Double.parseDouble(cols[i])));
   }
  }
 }
 public static class ColReducer extends
   Reducer<Text, DoubleWritable, Text, DoubleWritable> {
  public void reduce(Text key, Iterable<DoubleWritable> values,
    Context context) throws IOException, InterruptedException {
   double min = Integer.MAX_VALUE, max = 0;
   Iterator<DoubleWritable> iterator = values.iterator(); //Iterating 
   while (iterator.hasNext()) {
    double value = iterator.next().get();
    if (value < min) { 
     min = value;
    }
    if (value > max) {
     max = value;
    }
   }
   context.write(new Text(key), new DoubleWritable(min));
   context.write(new Text(key), new DoubleWritable(max));
  }
 }
 public static void main(String[] args) throws Exception {

  Configuration conf = new Configuration();
  Job job = new Job(conf, "\\ok.csv");
  job.setJarByClass(Test.class);
  FileSystem fs = FileSystem.get(conf);
  if (fs.exists(new Path(args[1]))) {
   fs.delete(new Path(args[1]), true);
  }
  job.setOutputKeyClass(Text.class);
  job.setOutputValueClass(DoubleWritable.class);

  job.setMapperClass(ColMapper.class);
  job.setReducerClass(ColReducer.class);

  job.setInputFormatClass(TextInputFormat.class);
  job.setOutputFormatClass(TextOutputFormat.class);

  FileInputFormat.addInputPath(job, new Path(args[0]));
  FileOutputFormat.setOutputPath(job, new Path(args[1]));
  System.exit(job.waitForCompletion(true) ? 0 : 1);
 }
}

最佳答案

ArrayIndexOutOfBoundsException 告诉您您正在尝试访问数组中大于数组维度的元素。

例如,给定

int[] arr = {1, 2, 3};

for (int i = 0; i < arr.length; i++) {
    System.out.println("index: " + i + "; value: " + arr[i]);
}

将输出

index: 0; value: 1
index: 1; value: 2
index: 2; value: 3

如果您尝试访问arr[3],则会抛出ArrayIndexOutOfBoundsException

检查代码中是否出现这些情况(调用 main 方法时使用哪些 args?)

关于java - 如何从 .csv 列获取最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57483052/

相关文章:

java - 切入点表达式 'abc(inString)' 包含不受支持的切入点原语 'call'

java - ... 中构造函数的参数 0 需要类型为 'org.springframework.web.client.RestTemplate' 的 bean,但无法找到

java - Vaadin 将值添加到列表

java - 以编程方式查找三个圆的交点

java - 数据库无法以html格式存储

java - 阻止 Android 中某些选定的菜单点以进行家长控制

java - 如何将多个对象持久化到数据库?

Java 扫描仪错误

java - 使用命令行从 Nexus 下载具有依赖项的 Maven Artifact

java - 为什么 Collections.sort 使用 Mergesort 而 Arrays.sort 不使用?