12 Replies Latest reply on Oct 15, 2007 2:48 AM by 800308

    using switch, scanner and char

    807600
      I need to write a program that takes a student?s letter grades as uppercase or lowercase char ( ?A?, ?a?, ?B?, ?b? etc ) from courses Maths, Chemistry and Physics and displays the average grade of the student.
      (I need to use switch to do this)

      P.S.

      Grade scale:
      A: 4.0
      B: 3.0
      C: 2.0
      D: 1.0
      F: 0


      Sample Run:
      Enter your Maths letter grade: B
      Enter your Physics letter grade: a
      Enter your Chemistry letter grade: d
      Your GPA is: 2.67
      Here are my codes but certainly there are lots of mistakes and missings.

      import java.util.Scanner; // Scanner is in java.util

      public class GradePointAverage {
           /**Main method*/
           public static void main(String[] args) {

                Scanner scanner = new Scanner(System.in); //using Scanner method to obtain input
                
                char letterGrade = scanner.next().charAt(0); //declaring a character as the student's grade
                
                double grade; //numeric grade

                double gradeAverage;
                
                if (grade == 4.0)
                     letterGrade = 'A';
                else if (grade == 3.0)
                     letterGrade = 'B';
                else if (grade == 2.0)
                     letterGrade = 'C';
                else if (grade == 1.0)
                     letterGrade = 'D';
                else if (grade == 0)
                     letterGrade = 'F';

                System.out.println("Enter your Maths letter grade: ");
                letterGrade = scanner.next();
      System.out.println("Enter your Physics letter grade: ");
      letterGrade = scanner.next();
      System.out.println("Enter your Chemistry letter grade: ");
      letterGrade = scanner.next();

      gradeAverage = (grade1 + grade2 + grade3)/3;

      System.out.println ("Your GPA is: " + gradeAverage);

                
                
                switch ( letterGrade ) {
                case 'A':
                case 'a':
                grade = 4.0;
                break;
                case 'B':
                case 'b':
                grade = 3.0;
                break;
                case 'C':
                case 'c':
                grade = 2.0;
                break;
                case 'D':
                case 'd':
                grade = 1.0;
                break;
                default:
                grade = 0;
                break;
                }

                }
           }
        • 1. Re: using switch, scanner and char
          807600
          Here are my codes but certainly there are lots of mistakes and missings.
          So what specifically do you need help with?
          • 2. Re: using switch, scanner and char
            807600
            javalava wrote:
                 /**Main method*/
            interesting...
            • 3. Re: using switch, scanner and char
              800308
              Volcanic coffee boy,

              Are you still stuck?

              This looks bunkum to me:
              if (grade == 4.0) letterGrade = 'A';
              else if (grade == 3.0) letterGrade = 'B';
              else if (grade == 2.0) letterGrade = 'C';
              else if (grade == 1.0) letterGrade = 'D';
              else if (grade == 0) letterGrade = 'F';

              especially when you consider that grade hasn't been set to anything (so it always has value 0).

              You need to assign a value to the variable before you test that value... which only seems reasonable, doesn't it?

              keith.

              Edited by: corlettk on Oct 15, 2007 2:17 AM
              • 4. Re: using switch, scanner and char
                807600
                I had fun with this one. Try handing this program in. ;-)
                import java.util.ArrayList;
                import java.util.List;
                import java.util.Scanner;
                
                public class GradeProgram
                {
                    private List<SubjectGrade> subjectGradeList = new ArrayList<SubjectGrade>();
                    private String[] subjects = {"Math", "Chemistry", "Physics"};
                    private Scanner scan = new Scanner(System.in);
                    private double gpa = 0.0;
                    
                    public void enterSubjectGrade(String subject)
                    {
                        boolean gradeValid = false;
                        while (!gradeValid)
                        {
                            System.out.print("Please enter your grade for " + subject + ": ");
                            Grade grade = Grade.getGrade(scan.nextLine().charAt(0));
                            if (grade != null)
                            {
                                subjectGradeList.add(new SubjectGrade(subject, grade));
                                int subjCount = subjectGradeList.size();
                                gpa = (grade.getScore() + gpa * (subjCount - 1)) / subjCount;
                                gradeValid = true;
                            }
                            else
                            {
                                System.out.println("Invalid grade entered, please try again.");
                                System.out.println();
                            }
                        }
                    }
                    
                    private void showResults()
                    {
                        System.out.printf("%10s %5s %6s\n",
                                "Subject", "Grade", "Score");
                        for (SubjectGrade subjectGrade : subjectGradeList)
                        {
                            System.out.printf("%10s %5s %6.3f\n", 
                                    subjectGrade.getSubject(),
                                    subjectGrade.getGrade().toString(),
                                    subjectGrade.getGrade().getScore());
                        }
                        System.out.println();
                        System.out.printf("%10s       %6.3f\n",
                                "GPA", gpa);
                    }
                
                    public void run()
                    {
                        for (int i = 0; i < subjects.length; i++)
                        {
                            enterSubjectGrade(subjects);
                }
                scan.close();
                System.out.println();
                showResults();
                }

                public static void main(String[] args)
                {
                GradeProgram gp = new GradeProgram();
                gp.run();
                }

                private class SubjectGrade
                {
                private String subject;
                private Grade grade;

                public SubjectGrade(String subject, Grade grade)
                {
                this.subject = subject;
                this.grade = grade;
                }

                public Grade getGrade()
                {
                return grade;
                }

                public String getSubject()
                {
                return subject;
                }
                }

                private enum Grade
                {
                A('A', 4.0),
                B('B', 3.0),
                C('C', 2.0),
                D('D', 1.0),
                F('F', 0.0);

                private char letter;
                private double score;

                private Grade(char letter, double score)
                {
                this.letter = letter;
                this.score = score;
                }

                public double getScore()
                {
                return score;
                }

                public char getLetter()
                {
                return letter;
                }

                public static Grade getGrade(char letter)
                {
                letter = Character.toUpperCase(letter);
                for (int i = 0; i < Grade.values().length; i++)
                {
                if (letter == Grade.values()[i].getLetter())
                {
                return Grade.values()[i];
                }
                }
                return null;
                }
                }
                }
                • 5. Re: using switch, scanner and char
                  800308
                  or this version
                  package forums;
                  
                  import java.io.Console;
                  import java.io.IOException;
                  
                  /**
                   * a program which takes a students' grades as letter A through F for courses:
                   * Maths, Chemistry & Physics; and displays the students' average grade.
                   */
                  class GradeAveragerator
                  {
                    private static final char[] GRADES = {'F','E','D','C','B','A'};
                    private static final Console console = System.console();
                  
                    public static void main(String[] args) {
                      try {
                        System.out.println("Please enter the students grade for each subject:-");
                        int sum = getGradeFor("Maths");
                        sum += getGradeFor("Chemistry");
                        sum += getGradeFor("Physics");
                        System.out.println("The students GPA is: "+String.format("%.2f",sum/3D));
                      } catch (Exception e) {
                        e.printStackTrace();
                      }
                    }
                  
                    private static int getGradeFor(String courseName) throws IOException {
                      while(true) {
                        String response = console.readLine("Grade for %s? ",courseName);
                        if (response == null || response.trim().length() == 0) throw new RuntimeException("User cancelled.");
                        int i = indexOf(Character.toUpperCase(response.trim().charAt(0)), GRADES);
                        if (i > 0) return(i);
                        System.out.println("Oops! Valid grades are A through F inclusive.");
                      }
                    }
                  
                    private static int indexOf(char value, char... args) {
                      for(int i=0; i<args.length; i++) {
                        if (args[i] == value) {
                          return(i);
                        }
                      }
                      return(-1);
                    }
                  
                  }
                  I generally find enums verbose and not very useful... until they get somewhat complex, in which case they're succinct, but hard to understand/maintain.
                  • 6. Re: using switch, scanner and char
                    807600
                    corlettk wrote:
                    I generally find enums verbose and not very useful... until they get somewhat complex, in which case they're succinct, but hard to understand/maintain.
                    Um,... that was my goal! to be verbose and complex. It was my nightly effort at "program-overkill". Your program, while nice, is too darn, how shall I say it,... usable and maintainable. The OP could actually turn yours in, but not my piece of junk.
                    • 7. Re: using switch, scanner and char
                      800308
                      or this version...
                      package forums;
                      
                      import java.io.Console;
                      import java.io.IOException;
                      
                      /**
                       * a program which takes a students' grades as letter A through F for courses:
                       * Maths, Chemistry & Physics; and displays the students' average grade.
                       */
                      class GradeAveragerator
                      {
                        private static final Console console = System.console();
                      
                        public static void main(String[] args) {
                          try {
                            System.out.println("Please enter the students grade for each subject:-");
                            int sum = getGradeFor("Maths");
                            sum += getGradeFor("Chemistry");
                            sum += getGradeFor("Physics");
                            System.out.println("The students GPA is: "+String.format("%.2f",sum/3D));
                          } catch (Exception e) {
                            e.printStackTrace();
                          }
                        }
                      
                        private static int getGradeFor(String courseName) throws IOException {
                          while(true) {
                            String response = console.readLine("Grade for %s? ",courseName);
                            if (response == null || response.trim().length() == 0) throw new RuntimeException("User cancelled.");
                            int grade = 'F' - Character.toUpperCase(response.trim().charAt(0));
                            if (grade >= 0 && grade <= 5) return(grade);
                            System.out.println("Oops! Valid grades are A through F inclusive.");
                          }
                        }
                      
                      }
                      We don't even need the GRADES array as long as we're using a western charset.

                      PS: There's a bug on F in my previous one... Guess I get an F then.
                      • 8. Re: using switch, scanner and char
                        807600
                        Actually there's a bug in this one too. There's no "E" grade here (see the OP's requirements). D- for you. :)
                        • 9. Re: using switch, scanner and char
                          800308
                          Um,... that was my goal! to be verbose and complex. It was my nightly effort at "program-overkill". Your program, while nice, is too darn, how shall I say it,... usable and maintainable. The OP could actually turn yours in, but not my piece of junk.
                          Oops. I completely misread the design goals, and misjudged you. I appologise.

                          Yep, I need to cut back on newbie homework. I realise that just doing it for them really doesn't help anyone, but it's just so much fun!

                          I'm Sad, I know.
                          • 10. Re: using switch, scanner and char
                            800308
                            Actually there's a bug in this one too. There's no "E" grade here (see the OP's requirements). D- for you. :)
                            Yeah but that's stupid fucking requirement, so, like any good programmer, I ignored it.
                            • 11. Re: using switch, scanner and char
                              807600
                              corlettk wrote:
                              Yep, I need to cut back on newbie homework. I realise that just doing it for them really doesn't help anyone, but it's just so much fun!
                              It's OK to do it, as long as it's in such a form that they can't turn it in without the teacher going, WTF?!? ;-)
                              • 12. Re: using switch, scanner and char
                                800308
                                as long as it's in such a form that they can't turn it in
                                Point taken.