< Java Programming Part 2 | Java & Friends | Java Programming Part 4 >


 

 

Using jGRASP Java IDE: Java Programming Part 3

 

 

Content:  Java Program Examples Part 3

 

11.    Write a program that allows the user to enter students’ names followed by their test scores and outputs the following information (assume that maximum number of students is 50):

 

a.      The average score.

b.     Names of all students whose test scores are below the average, with an appropriate message.

c.      Highest test score and the name of all students having the highest score.

 

Use two arrays to store the student names and scores respectively and then manipulate the array contents.

 

import java.util.Scanner;

// for double formatting

import java.text.DecimalFormat;

 

public class StudentScore

{

   //---------------------------------------------------------

   // Calculate student score and basic report

   //---------------------------------------------------------

  

   public static void main(String[] args)

   {

      // an array of double to store student's score

      double [] studentscore = new double[50];

      // an array of String object to store student name

      String [] studentname = new String[50];

      double studentavg = 0.0, sumscore = 0.0, averagescore = 0.0, highestscore =0.0;

      // index

      int i = 0, j = 0, k = 0, counter = 1;

     

      Scanner readname = new Scanner(System.in);

      Scanner readscore = new Scanner(System.in);

      // prompt for inputs: Student name and score

      System.out.println("Enter student name and score, 'Q' & 0 to stop: ");

      // read and store student name and score for 1st input...

      studentname[i] = readname.nextLine();

      studentscore[i] = readscore.nextDouble();

     

      // read and store next student name and score

      do

      {

         i++;

         counter++;

         System.out.println("Enter student name and score, 'Q/q' & 0 to stop: ");

         studentname[i] = readname.nextLine();

         studentscore[i] = readscore.nextDouble();

         // until the Q or q and 0 are entered...

      }  while(((studentname[i].compareTo("Q") != 0) || (studentname[i].compareTo("q") != 0)) && (studentscore[i] != 0));

     

      // formatting the double output to two decimal places

      DecimalFormat fmt = new DecimalFormat("0.##");

      // some cosmetic formatting...
      System.out.println("=================REPORT====================");

      System.out.println("Student Name\tScore");

      System.out.println("------------\t-----");

      // set initial value of the highest score to the 1st array element

      // and then compare 1 by 1 in the for loop...

      highestscore = studentscore[0];

      for(k=0;k<=i-1;k++)

      {

         // print all the student names and their respective scores

         System.out.println(studentname[k]+"\t\t"+fmt.format(studentscore[k]));

         // summing up all the score for average calculation

         sumscore = sumscore + studentscore[k];

         // determining the highest score

         if(highestscore < studentscore[k])

            highestscore = studentscore[k];

      }

      // calculate class average score

      System.out.println();

      System.out.println("The number of student is " + (counter-1));

      averagescore = sumscore /  (counter-1);

      System.out.print("The average score for this class is " + fmt.format(averagescore));

      // some cosmetic formatting...

      System.out.println();

      System.out.println("================================================");

      System.out.println("Below The Average Students! Work Harder! ");

      System.out.println("================================================");

      System.out.println("Student Name\tScore");

      System.out.println("------------\t-----");

      // list down all the below average students

      for(k=0;k<=i-1;k++)

      {

         if(studentscore[k] < averagescore)

            System.out.println(studentname[k] + "\t\t" + fmt.format(studentscore[k]));

      }
     
// some cosmetic formatting...

      System.out.println("================================================");

      System.out.println("Top Scorer Student! Congratulation!");

      System.out.println("================================================");

      System.out.println("Student Name\tScore");

      System.out.println("------------\t-----");

      // list down all the highest mark students

      for(k=0;k<=i-1;k++)

      {

         if(studentscore[k] == highestscore)

            System.out.println(studentname[k] + "\t\t" + fmt.format(studentscore[k]));

      }

   }

}

 

An output samples:

 

Enter student name and score, 'Q' & 0 to stop:

Jodie Foster

79.50

Enter student name and score, 'Q/q' & 0 to stop:

Ahmad Nazri

99.9

Enter student name and score, 'Q/q' & 0 to stop:

Jaya Sakti

80.35

Enter student name and score, 'Q/q' & 0 to stop:

Laila Abu

58.9

Enter student name and score, 'Q/q' & 0 to stop:

Irene Khoh

65.5

Enter student name and score, 'Q/q' & 0 to stop:

Azmir Khan

45.30

Enter student name and score, 'Q/q' & 0 to stop:

John Jr.

99.9

Enter student name and score, 'Q/q' & 0 to stop:

Mikerisan

55.70

Enter student name and score, 'Q/q' & 0 to stop:

q

0

=================REPORT====================

Student Name        Score

------------        -----

Jodie Foster        79.5

Ahmad Nazri         99.9

Jaya Sakti          80.35

Laila Abu           58.9

Irene Khoh          65.5

Azmir Khan          45.3

John Jr.            99.9

Mikerisan           55.7

 

The number of student is 8

The average score for this class is 73.13

================================================

Below The Average Students! Work Harder!

================================================

Student Name        Score

------------        -----

Laila Abu           58.9

Irene Khoh          65.5

Azmir Khan          45.3

Mikerisan           55.7

================================================

Top Scorer Student! Congratulation!

================================================

Student Name        Score

------------        -----

Ahmad Nazri         99.9

John Jr.            99.9

 

12.    Write the definition of a class that has the following properties:

 

a.      The name of the class Secret

b.     The class has four data members: name (String), age (int), weight (int) and height (double)

c.      The class has the following methods:

 

                                      i.      print  - outputs the values of all data members with appropriate titles.

                                    ii.      setName – method to set name to a new value

                                  iii.      setWeight – method to set the age to a new value

                                  iv.      setHeight - method to set height to a new value

                                    v.      getName - method to return the name

                                  vi.      getAge - method to return the age

                                vii.      getWeight - method to return the weight

                              viii.      getHeight - method to return the height

                                  ix.      default constructor – the default value of name is the empty string “”, the default values for age, weight and height are 0.

                                    x.      constructor with parameters – sets the values of the data name, age, weight and height to the values specified by user

 

d.     Write the definitions of the methods of class Secret as described in part c.

 

 

This is just a working java program skeleton of class definition and object instantiation.

 

import java.util.Scanner;

 

//---------------------------------------------------------

// class Secret, nothing is secret here...

//---------------------------------------------------------

 

public class Secret

{

   // data declarations, variables with their own data types

   // initialized with values that will be used as default constructor's

   // values if there is no one to be found...

   String name = "";

   int age = 0, weight = 0;

   double height = 0.0;

  

   // constructor that will overwrite the default one...

   public Secret(String coname, int coage, int coweight, double coheight)

   {

      Scanner readdata = new Scanner(System.in);

     

      System.out.print("Enter your name: ");

      coname = readdata.nextLine();

      setName(coname);

      System.out.print("Enter your age: ");

      coage = readdata.nextInt();

      setAge(coage);

      System.out.print("Enter your weight: ");

      coweight = readdata.nextInt();

      setWeight(coweight);

      System.out.print("Enter your height: ");

      coheight = readdata.nextDouble();

      setHeight(coheight);

      print();

   }

  

   //---------------------------------------------------------

   // The following methods will be used when the instantiated

   // object call them from the main().....

   // in this program, however all call from main() will be overwritten

   // by the constructors....

   //---------------------------------------------------------

  

   // setName method() - set name to a new value

   public void setName(String yourname)

   {

      name = yourname;

   }

  

   // setAge method() - set the age to a new value

   public void setAge(int yourage)

   {

      age = yourage;

   }

  

   // setWeight method() - set the weight to a new value

   public void setWeight(int yourweight)

   {

      weight = yourweight;

   }

  

   // setHeight method() - set the height to a new value

   public void setHeight(double yourheight)

   {

      height = yourheight;

   }

  

   // getName method() - return the name

   public String getName()

   {

      return name;

   }

  

   // getAge method() - return the age

   public int getAge()

   {

      return age;

   }

  

   // getWeight method() - return the weight

   public int getWeight()

   {

      return weight;

   }

  

   // getHeight method() - return the height

   public double getHeight()

   {

      return height;

   }

  

   // print method() - output all data to standard output

   public void print()

   {

      System.out.println();

      System.out.println("Your name is: " + getName() + ".");

      System.out.println("Your age is: " + getAge() + " years old.");

      System.out.println("Your weight is: " + getWeight() + " kgs.");

      System.out.println("Your height is: " + getHeight() + " cms.");

   }

 

   // main() method - the start of this program execution point

   public static void main(String[] args)

   {

      // instantiate an object of type Secret class

      // giving some dummy values that will be overwritten by

      // the 'Constructor with parameters'.

      // this instantiation will invoke Constructor with parameters

      Secret mysecret = new Secret("Nazri",30,56,165);

     

      // other codes.....

   }

}

 

An output samples:

 

Enter your name: Ahmad Nazri bin Zainol

Enter your age: 48

Enter your weight: 53

Enter your height: 165

 

Your name is: Ahmad Nazri bin Zainol.

Your age is: 48 years old.

Your weight is: 53 kgs.

Your height is: 165.0 cms.

 

Enter your name: Meg Ryan Jr.

Enter your age: 40

Enter your weight: 50

Enter your height: 170

 

Your name is: Meg Ryan Jr..

Your age is: 40 years old.

Your weight is: 50 kgs.

Your height is: 170.0 cms.

 

13.    Implement a class Rectangle that has methods getArea(), getPerimeter() and getDiagonal(). In the constructor, supply the length and width of the rectangle. Write a program that asks the user for the length and width of a rectangle. Then creates an object of Rectangle and prints its area, perimeter and diagonal length. (Use the Pythagorean formula to calculate length of the diagonal)

 

Another user defined class and object with 3 methods that do their own specific tasks.

 

import java.util.Scanner;

import java.text.DecimalFormat;

 

//---------------------------------------------------------

// class Rectangle: Area, Perimeter and Diagonal

//---------------------------------------------------------

// For rectangles with the sides a, b, is:

// area = a * b

// perimeter = 2*(a + b)

// diagonal = root of ((a*a)+(b*b))

 

public class Rectangle

{

   // member variables, used as default constructor values

   // if constructor not provided

   double   height = 0.0 ;

   double   width = 0.0;

  

   // constructor

   Rectangle(double h, double w)

   {

      height = h;

      width = w;

   }

  

   // get the rectangle perimeter

   public double getPerimeter(double h, double w)

   {

      return   2*(h+w);

   }

    // get the rectangle area

   public double getArea(double h, double w)

   {

      return   (h*w);

   }

     // get the rectangle diagonal

   public double getDiagonal(double h, double w)

   {

      return   Math.sqrt(((h*h)+(w*w)));

   }

 

   // main() method - the start of this program execution point

   public static void main(String[] args)

   {

      double recheight = 0.0, recwidth = 0.0;

     

      // instantiate a standard input object

      Scanner readuserinput = new Scanner(System.in);

      // prompt user for rectangle's height and width

      System.out.print("Enter rectangle height and width (e.g: 10 10): ");

      // read and store rectangle's height and width

      recheight = readuserinput.nextDouble();

      recwidth = readuserinput.nextDouble();

      // instantiate and initialize the myrectangle object

// of type rectangle class

      Rectangle myrectangle = new Rectangle(recheight, recwidth);

      // do some formatting for the double

      DecimalFormat fmt = new DecimalFormat("0.##");

      // print rectangle's area, perimeter and diagonal to standard output

      System.out.println("The rectangle area is: " + fmt.format(myrectangle.getArea(recheight,recwidth)));

      System.out.println("The rectangle perimeter is: " + fmt.format(myrectangle.getPerimeter(recheight,recwidth)));

      System.out.println("The rectangle diagonal is: " + fmt.format(myrectangle.getDiagonal(recheight,recwidth)));

}

}

 

An output samples:

 

Enter rectangle height and width (e.g: 10 10): 10 10

The rectangle area is: 100

The rectangle perimeter is: 40

The rectangle diagonal is: 14.14

 

Enter rectangle height and width (e.g: 10 10): 12.5 10.5

The rectangle area is: 131.25

The rectangle perimeter is: 46

The rectangle diagonal is: 16.32

 

Enter rectangle height and width (e.g: 10 10): 50.2 21.7

The rectangle area is: 1089.34

The rectangle perimeter is: 143.8

The rectangle diagonal is: 54.69

 

 

 

 

 

 

 

 

 

jGRASP the Java IDE & Java Programming: Part 0 | Part 1 | Part 2 | Part 3 | Part 4


 

< Java Programming Part 2 | Java & Friends | Java Programming Part 4 >