#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    1
    Rep Power
    0

    Input grade percent, output letter grade 1 line error


    getting an error on line 7 "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at grades.Grades.main(Grades.java:7)"
    Code:
    public class Grades {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            int score = Integer.parseInt
                    (args[0]);
            char grade;
            if (score >=90)
            {grade = 'A';
            }
            else if (score >=80) 
            {grade = 'B';
            } else if (score >= 70) {
    grade = 'C';
    } else if (score >= 60) {
    grade = 'D';
    } else {
    grade = 'F';
    }
    System.out.println ("The grade is " + grade + ".");
            }
        }
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    Hi,

    are you sure you've passed command line arguments to the program? Because it's telling you that "args" is empty.

    Comments on this post

    • ishnid agrees
  4. #3
  5. Daniel Schildsky
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Mar 2004
    Location
    KL, Malaysia.
    Posts
    1,554
    Rep Power
    1621

    Alternative coding style, after fixing the error


    You should somehow check for presence of arguments before proceeding with further processing:

    Java Code:
     
     
    public static void main(String[] args) {
     
        if(args.length == 0) {
           System.out.println("No arguments specified!");
           System.exit(1);
        }
     
    //the rest of the codes followed..
     
    }



    On a side note, instead of a long-winded if..else statement, you may use a switch..case statement for brevity:
    java Code:
     
        int tenths = score / 10;
        switch(tenths) {
             case 10:
             case 9:   grade = 'A'; break;
             case 8:   grade = 'B'; break;
             case 7:   grade = 'C'; break;
             case 6:   grade = 'D'; break;
             default:   grade = 'F'; break;
        }


    The logic behind this is simple: if the tenths of the score is 9 (from 90-99) and 10 (means 100), then assign 'A' to the variable 'grade'. and likewise for the rest of the grades. integer variable tenths stores only the integer part of the result of the score division by 10.

    However, this alternative coding style is only applicable if the score from the command line does not exceed 100.
    When the programming world turns decent, the real world will turn upside down.

IMN logo majestic logo threadwatch logo seochat tools logo