对于从数组

时间:2015-08-09 14:52:13

标签: java arrays string sorting substring

我正在尝试为使用文本文件的学生打印两个单独的考试标记。 以下是文本文件的屏幕截图:

第一列是学生ID,以下两列是考试成绩

以下是执行该计算和打印的代码:

       //for loop that does calculations and prints
    for(int i = 0; i < arraySize;i++){
        String markOneFull = studentExamOneArray[i];
        String markOneString = markOneFull.substring(5,7);
        double markOne = Double.parseDouble(markOneString);
        examOneNoID[i]= markOne;

        String markTwoFull = studentExamTwoArray[i];
        String markTwoString = markTwoFull.substring(8,10);
        double markTwo = Double.parseDouble(markTwoString);
        examTwoNoID[i] = markTwo;

  /*      String markThreeFull = studentExamThreeArray[i];
        String markThreeString = markThreeFull.substring(5,10);
        double markThree = Double.parseDouble(markThreeString);
        examThreeNoID[i] = markThree;

        String markFourFull = studentExamFourArray[i];
        String markFourString = markFourFull.substring(5,10);
        double markFour = Double.parseDouble(markFourString);
        examFourNoID[i] = markFour;
   */     

        // Aggregate Mark

        double aggregate = (examOneNoID[i] + examTwoNoID[i])/2;
        DecimalFormat oneDigit = new DecimalFormat("#,##0.0");


        //time to write
        write.println(studentArray[i] + "\nAB101: " + examOneNoID[i] + " " + " AB102: " + examTwoNoID[i] + " Overall Mark: " + oneDigit.format(aggregate));
        write.println("----------------------------------------");
    }
    write.close();


}

当我运行程序时,我收到一条错误消息:

 Exception in thread "main" java.lang.NumberFormatException: empty String
  at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
  at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
  at java.lang.Double.parseDouble(Double.java:538)
  at MarksProcessing.main(MarksProcessing.java:42)

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

    Scanner sc = new Scanner(new File(fileName));

    int i = 0;
    while (sc.hasNext())
    {
        students[i] = sc.nextInt();
        studentExamOneArray[i] = sc.nextDouble();
        studentExamTwoArray[i] = sc.nextDouble();


        double aggregate = (studentExamOneArray[i] + studentExamTwoArray[i])/2;
        DecimalFormat oneDigit = new DecimalFormat("#,##0.0");
        System.out.println("Student: " + students[i] + " FirstGrade: " + studentExamOneArray[i] + " SecondGrade: " + studentExamTwoArray[i] + " Overal: " + oneDigit.format(aggregate));
        i++;
    }

现在,您不需要子串等。您知道文件的结构与成绩或文件是什么。而且你不需要额外的数组(你用一个用于字符串,然后用一个用于双打等等)。只需将数字读入数组,然后进行数学运算并打印。

答案 1 :(得分:0)

我认为,指定的问题很容易处理。我们可以看到,在这里我们将字符串类型解析为不同类型的数据类型,因此我们应该尝试捕获数字格式异常。