Object-Oriented Programming with Java, part I – Exercise 18

This program outputs a users grade based on their input.

My Code

import java.util.Scanner;

public class GradesAndPoints {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);    // User input
        System.out.println("Type the points [0-60]: ");
        int points = Integer.parseInt(reader.nextLine());

        System.out.println("");                     // White space

        if (points > 49) {                           // Loop to output result
            System.out.println("Grade: 5");
        } else if (points > 44) {
            System.out.println("Grade: 4");
        } else if (points > 39) {
            System.out.println("Grade: 3");
        } else if (points > 34) {
            System.out.println("Grade: 2");
        } else if (points > 29) {
            System.out.println("Grade: 1");
        } else {
            System.out.println("failed");
        }

    }
}

Model Code

import java.util.Scanner;

 

public class GradesAndPoints {

 

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

 

        System.out.print("Type the points [0-60]:  ");

        int points = Integer.parseInt(reader.nextLine());

        

        System.out.print("Grade: ");

        if (points < 30) {

            System.out.println("failed");

        } else if (points < 35) {

            System.out.println(1);

        } else if (points < 40) {

            System.out.println(2);

        } else if (points < 45) {

            System.out.println(3);

        } else if (points < 50) {

            System.out.println(4);

        } else {

            System.out.println(5);

        }    

    }

}

 

Comments

The model code prints out the Grade: part of the program before the loop by using System.out.print instead of System.out.println which saves quite a lot of copying.

Leave a comment