将字符串数组更改为整数

时间:2019-02-22 20:16:49

标签: java arrays

我正在尝试创建一个采用String数组的方法,然后将元素复制到Integer数组中,然后计算平均值。不确定im是否在正确的路径上,或者这是完全错误的。

 public static double CalculateAvg(String [] Grades)
   {
    int []Exams = new int[Grades.length];
    double AVG =0;
    int sum = 0;
    int j = 0;
    for (int i = 0; i <= Grades.length; i++)
    {
        Exams[i] = Integer.parseInt(Grades[i]);
        Exams[i] = j;
        sum +=j;
        AVG= (double)sum/4;
    }
    //return AVG;
   }
}

3 个答案:

答案 0 :(得分:5)

您有很多冗余变量。试试:

public static double CalculateAvg(String [] Grades) {
    double sum = 0;
    for (int i = 0; i < Grades.length; i++) {
        sum += Integer.parseInt(Grades[i]);
    }
    return sum/Grades.length;
}

通过流api可以完成它。仅出于您的教育目的:

double avg = Arrays.stream(Grades)
      .mapToInt(Integer::valueOf)
      .average().orElse(0);

答案 1 :(得分:0)

计算平均值需要除以元素数 我认为这是您正在寻找的

           public static double CalculateAvg(String [] Grades)
           {
              int []Exams = new int[Grades.length];
              double AVG =0;
              int sum = 0;
              int j = 0;
              for (int i = 0; i <= Grades.length; i++)
               {
                 Exams[i] = Integer.parseInt(Grades[i]);

                 AVG= (double) Exams[i]/Grades.length;
                 }
            return AVG;
           }

答案 2 :(得分:0)

您还可以尝试如下所示的Java 8 Streams和Lambda表达式:

    public static double calculateAverage(String[] grades)
    {
    return Arrays.stream(grades)
                 .map(grade->Double.parseDouble(grade))
                 .reduce(0.0,(sum, grade) -> sum + grade)/grades.length;
    }