一个方法中的两个数组乘法

时间:2013-04-29 14:09:28

标签: java arrays jcreator

我需要计算grade[0]percentage1[0]的乘法,然后打印结果。有人能帮助我吗?

LaboratoryExam.java

import java.util.*; 
public class LaboratoryExam {

  static Scanner glad=new Scanner(System.in);
  static double grades[]=new double[5];
  static double percentage1[]=new double[5];
  static double comp[]=new double[5];
  static double sum=0;

  public static void main(String[] args) {



    System.out.print("Enter 5 grades: ");

    for(int i=0; i<grades.length; i++){

      grades[i]=glad.nextDouble();
    }


    Percentage();
    compute(grades,percentage1);
    System.out.println("\nSum is: " + sum);
  }

  public static double[] Percentage(){
    double Percentage;
    System.out.print("\nEnter 5 Percentage: ");

    for(int p=0; p<percentage1.length; p++)
      percentage1[p]=glad.nextDouble();

    return percentage1;
  }

  public static double compute(  double[] grades,  double[] percentage1 ){

    for(int i=0; i<comp.length;i++){

      double comp=grades[0]*percentage1[1];
      System.out.println("Equivalent: "+sum);
      double sum=comp+comp;
    }
    return sum;
  }

}

3 个答案:

答案 0 :(得分:0)

这几乎是好的。确保在for循环之外声明sum变量,以便在循环的每次迭代中保留其值。还可以使用数组索引来访问正确的值。将其更改为:

public static double compute(  double[] grades,  double[] percentage1 ){
  double sum = 0;
  for(int i=0; i<comp.length;i++){

    comp[i]=grades[i]*percentage1[i];
    System.out.println("Equivalent: "+comp[i]);
    sum += comp[i];
  }
  return sum;
}

此外,在您的主要方法中,请将其设为:

sum = compute(grades,percentage1);

答案 1 :(得分:0)

compute方法中,您获得了grades[0]percentage1[1]的所有迭代产品。相反,您应该使用i循环中所述的for索引上的元素:

for(int i=0; i<comp.length;i++) {
    double comp = grades[i]*percentage1[i];

另外,你正在计算错误的总和:

for(int i=0; i<comp.length;i++) {
    double sum=comp+comp;
}

在这里,您要隐藏之前声明的static double sum,因此在执行return sum;时您将始终获得0。您应该使用类中声明的sum变量:

for(int i=0; i<comp.length;i++) {
    //note: no re-declaration of sum variable
    //also fixed the sum calculation
    sum += comp;
}

最后,您的代码将如下所示:

for(int i=0; i<comp.length;i++) {
    double comp=grades[i]*percentage1[i];
    comp[i] = comp;
    sum += comp;
    System.out.println("Equivalent: "+sum);
}
return sum;

答案 2 :(得分:0)

您应该使用grades[i]percentage1[i]进行乘法运算。在这里,你只是一遍又一遍地乘以相同的数字。试试这个:

double comp=grades[i]*percentage1[i];

另外,我认为你不打印正确的东西,因为你似乎想要打印乘法的结果。试试这个:

System.out.println("Equivalent: "+ comp);

最后,我认为最好从for:声明comp和sum:

public static double compute(  double[] grades,  double[] percentage1 ){
    double comp;
    double sum;
    for(int i=0; i<comp.length;i++){
        comp=grades[0]*percentage1[1];
        System.out.println("Equivalent: "+sum);
        sum=comp+comp;
    }
    return sum;
}