I am trying to take name input from another class (i.e. from "StudentMarks.class"). I am taking all the user inputs from main class (i.e. from "StudentMarks.class"), but the declaration is done in another class (i.e. value.class).
Although I have initialized the variable size which will be the size of my string array, while taking input for user name it is putting error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at studentmarks.StudentMarks.main(StudentMarks.java:53)
System.out.printf("\nEnter names : ");
for(int i=0; i<(mar.size); i++){
mar.name[i]= sc.nextLine(); // Getting error here
}
I know this code is messy because I am in learning phase and I want to try all possible way to take input generate output etc. Generally, I am experimenting with my code.
My code here
package studentmarks;
import java.util.*;
class value{
int size; // variable to declare size of my array
String name[]=new String[size]; //take name input from user
float marks[]= new float[size]; //take marks input from user
float sum=0;
double total(){
for(float i: marks)
sum+=i;
return sum;
}
double average(){
return sum/(marks.length);
}
char grade(){
if(average()>=90)
return 'A';
else if(average()>=80 && average()<90)
return 'B';
else
return 'C';
}
}
public class StudentMarks {
public static void main(String[] args) {
// TODO code application logic here
Scanner sc=new Scanner(System.in);
value mar=new value();
System.out.printf("Enter size : ");
mar.size= sc.nextInt(); // taking user input to define array size declared in value.class
System.out.println(mar.size); // checking size was correctly intitalized or not
System.out.printf("\nEnter names : ");//taking name input here (array was declared in value.class)
for(int i=0; i<(mar.size); i++){
mar.name[i]= sc.nextLine(); //Getting array index error here
}
System.out.printf("\nEnter marks : ");//taking marks input here (array was declared in value.class)
for(int i=0; i<mar.size; i++){
mar.marks[i]= sc.nextFloat();
}
//printing result
for(String i: mar.name){
System.out.println(i);
}
System.out.println(mar.average());
System.out.println(mar.grade());
}
}