运行时出现Java编码错误,但似乎是正确的

时间:2018-08-25 08:20:08

标签: java

我编写了一个Java程序,以读取一些学生姓名,标记的内置标记。给他们评分并显示学生姓名,分数和成绩。但是,当我尝试运行代码时,会发生以下错误。

  

“线程“主”中的异常” java.lang.ArrayIndexOutOfBoundsException:0       在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]);
        }
    }
 }

1 个答案:

答案 0 :(得分:1)

您正在尝试在grade[i]为空时打印grade。您应该首先使用其大小初始化grade,然后分配值以使其能够打印。

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]);
        }
    }
}