Where is my mistake? for loops in array


#1


Hey Guys, i'm writing a program that stores 3 students names in an array and their grades in 3 subjects in another one
and then calculate the average of each student, and then finding the highest average and the lowest average.
i have done the first part which calculates the average
but when i put the code for finding the maximum, it skips calculating the average of the second and third students, and declare that the first student had the highest average.
i tried to find the max outside the loop, but it gives an error message.

can you please spot my mistake? .


import java.util.*; 
public class New { 
public static void main(String[] args) { 
Scanner scan = new Scanner(System.in); 
String name[]=new String[3]; 
float grade[][]=new float[3][3]; 
float avg[]=new float[3]; 
int i, j; 
for (i=0; i<=2;i++){ 
System.out.println("Enter Student name:"); 
name[i]= scan.nextLine(); 
for (j=0; j<=2;j++){	
grade[i][j]= scan.nextInt(); 
scan.nextLine();}} 

for ( i=0; i<name.length; i++){ 
System.out.print("grades of ["+name[i]+"]"+"\t"); 
for ( j=0; j<3; j++) 
System.out.print(grade[i][j]+"\t"); 
System.out.println(); 
} 
for ( i=0; i<name.length; i++){ 
	float sum=0;
for ( j=0; j<3; j++) 
	
sum+=grade[i][j]; 
avg[i]=sum/3; 

System.out.println("Average of student "+name[i]+" is " +avg[i]);	
//float max=avg[i]; int pos=0;
//for (i=1; i<=2; i++)
//	if (avg[i]>max){
	//	max = avg[i];
   	//pos=i;}

	//System.out.println("Highest Average is "+name[pos]);

}

} 
}


#2

Hi there,

Not really sure if this is the right place to be having this discussion but nonetheless I figured out what was happening in regards to your code.

First of all. You can take all that commented code out of the for loop, there's no logical reason for it to be there.


That being said, the real problem lies with your max float defintion.

float max=avg[i]

i at this point in the program is assigned to the value of 3 because the loop before this definition concluded by saying i++. Just remember that for loops > declare a variable > test the condition > do the code > then iterate.

Therefore what you're trying to do is assign avg[3] to max. But avg[3] doesn't exist. So the jre will throw an exception declaring that the float can not be assigned because the array index is out of bounds .

You should instead change the i to a 0 because we want to start from the first index anyways.

Hope that helps.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.