Java 2维数组和平均值

时间:2014-11-30 20:49:15

标签: java arrays average

有人可以帮我完成这项功课吗?

我尝试了一些东西,但我不确定我的解决方案是否涵盖了所有任务。 我必须编写一个Java程序,它使用第5学期的标记初始化一个二维数组(如你所知,只有5个标记)n个学生(用户应该输入学生数)。

程序应该输出结果:

  1. 第五学期所有学生的平均成绩;
  2. 平均成绩最高的学生人数;
  3. 平均成绩最低的学生人数;
  4. 平均成绩高于所有学生平均成绩的学生人数;
  5. 平均成绩低于所有学生平均成绩的学生人数;
  6. 该计划应进行如下数据验证:学生的分数应在2到6之间,学生人数不应超过30分。

    到目前为止,这是我的解决方案:

    package ocenki;
    
    
    public static void main(String[] args) {
    
     Scanner scan = new Scanner (System.in ) ;
     System.out.println ("Enter notes here:") ;
    
     double [] marks= new double [5] ;
    
     for ( int i=0; i<=4; i++)   
     {
         System.out.println ("Please, input mark for " + i +(" subject")) ; 
    
         marks[i] = scan. nextDouble () ; 
    
         while (marks[i]<2 || marks[i]>6)
         {
             System.out.println ("Please, input marks between 2 and 6:") ;
             marks[i] = scan.nextDouble () ;
         }
     }
    
     double sum=0; 
     double min=marks[0];
     double max=marks[0];
    
     for ( int i=0; i<=4; i++)
     {
         sum = sum+marks[i] ; 
         if(marks[i]>max)
         {
             max=marks[i];
         }
         if(marks[i]<min)
         {
             min=marks[i];
         }       
     }
     System.out.println("The average is " + sum/5 + ", the minimum is " + min + " and the maximum is " + max); 
    }
    

1 个答案:

答案 0 :(得分:0)

请找到Q-4和Q-5的解决方案

<强>解决方案

    double avg= sum/5;
 for ( int i=0; i<=4; i++)
 {
     if(marks[i]>avg)
     {
         moreAvg++;
     }
     if(marks[i]<avg)
     {
         lessAvg++;
     }   
 }

完整代码 -

public static void main(String[] args) {

 Scanner scan = new Scanner (System.in ) ;
 System.out.println ("Enter notes here:") ;

 double [] marks= new double [5] ;

 for ( int i=0; i<=4; i++)   
 {
     System.out.println ("Please, input mark for " + (i+1) +(" subject")) ; 

     marks[i] = scan. nextDouble () ; 

     while (marks[i]<2 || marks[i]>6)
     {
         System.out.println ("Please, input marks between 2 and 6:") ;
         marks[i] = scan.nextDouble () ;
     }
 }

 double sum=0; 
 double min=marks[0];
 double max=marks[0];
 int lessAvg=1,moreAvg=0;
 for ( int i=0; i<=4; i++)
 {
     sum = sum+marks[i] ; 
     if(marks[i]>max)
     {
         max=marks[i];
     }
     if(marks[i]<min)
     {
         min=marks[i];
     }       
 }

 double avg= sum/5;
 for ( int i=0; i<=4; i++)
 {
     if(marks[i]>avg)
     {
         moreAvg++;
     }
     if(marks[i]<avg)
     {
         lessAvg++;
     }   
 }

 System.out.println("The average is " +avg + ", the minimum is " + min + " and the maximum is " + max);
 System.out.println("4.The number of students with an average grade greater than the average grade of all students"+moreAvg);
 System.out.println("5.The number of students with an average grade less than the average grade of all students"+lessAvg);
}