Kavishka Hirushan
Kavishka Hirushan

Reputation: 59

java coding error from running But seems to be correct

I code a java program to read a inbuilt marks of some students names, marks. Grade them & show along with the student name, marks & grade. But when I tried to run the code the following error occurs.

"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Namemarksgrade.main(Namemarksgrade.java:36) "``

 public class Namemarksgrade {
  public static void main(String args[]){

    String name[]= {"st1","st2","st3","st4","st5","st6","st7","st8","st9","st10"};

   int marks[] = {10,20,3,65,68,23,24,21,45,96};
    char grade[]={};
    /*for(int i =0; i<name.length;i++){

    System.out.println(name[1]);
    }
    */
    for(int i=0;i<marks.length;i++){
        if(marks[i]>=75){
           // grade[i] = 'A';
    }
        else if (marks[i]<74 && marks[i]>65 ){
           // grade[i]='B';
        }
        else if (marks[i]<64 && marks[i]>55){
           // grade[i]= 'C';
        }
        else{
           // grade[i] = 'D';
        }
        System.out.println(grade[i]);

        } 
    System.out.println("Name"+"\t"+"Marks"+"\t"+"Grade");
        for(int j =0; j<name.length; j++){
            System.out.println(name[j]+"\t"+marks[j]+"\t"+ grade[j]);
        }
    }
 }

Upvotes: 0

Views: 47

Answers (1)

kzharas210
kzharas210

Reputation: 500

You are trying to print grade[i] while grade is empty. You should first initialize grade with its size and then assign value to be able to print it.

public class Namemarksgrade {
    public static void main(String args[]) {

        String[] name = {"st1", "st2", "st3", "st4", "st5", "st6", "st7", "st8", "st9", "st10"};
        int[] marks = {10, 20, 3, 65, 68, 23, 24, 21, 45, 96};
        char[] grade = new char[10];

    /*for(int i =0; i<name.length;i++){
        System.out.println(name[1]);
    }*/

        for (int i = 0; i < marks.length; i++) {
            if (marks[i] >= 75) {
                grade[i] = 'A';
            } else if (marks[i] < 74 && marks[i] > 65) {
                grade[i] = 'B';
            } else if (marks[i] < 64 && marks[i] > 55) {
                grade[i] = 'C';
            } else {
                grade[i] = 'D';
            }
            System.out.println(grade[i]);

        }

        System.out.println("Name" + "\t" + "Marks" + "\t" + "Grade");
        for (int j = 0; j < name.length; j++) {
            System.out.println(name[j] + "\t" + marks[j] + "\t" + grade[j]);
        }
    }
}

Upvotes: 1

Related Questions