Skip to main content

Programming in Java Netbeans - A Step by Step Tutorial for Beginners: Lesson 29

Danson Wachira is a certified Trainer in Computer Science, Information Technology and related studies.

Table of Contents

<< Lesson 28 | Lesson 30 >>

Lesson 29: Java classes and methods

In Lesson 28, we learnt how to create Java constructors and setter methods. We saw how we can use constructors to set default values and how we can use setter methods to assign new values that overwrite the default values.

In this lesson, we shall continue from where we left in Lesson 28 and learn more on what we can do with Java classes. For you to understand the concepts used in this particular lesson, I recommend that you revisit Lesson 27 and Lesson 28.

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-29

We are going to add three more methods in the Examination class. Each of these methods will perform a specific function.

One method will return the Examination name another will return the score while the last method will return the grade.

We shall also use control structures such as IF ... ELSE statements to add functionality to these methods. Remember the final code we had in the class ExamDetails? Here, have a look at it again:

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-29

Still in the ExamDetails class we are going to add another method that will return the Examination name. The method will receive a two characters input and use IF … ELSE statement to return the full examination name. For example if we pass “VB” the method should return “Visual Basic .NET”. Add the following code in the ExamDetails class. You can either type or copy and paste the code.

Java classes and methods

package examination;

public class ExamDetails {
    private String Student_name;
    private String Exam_name;
    private String Exam_score;
    private String Exam_grade;
    
    ExamDetails(){
       Student_name = "No name given";
       Exam_name = "unknown";
       Exam_score = "No score";
       Exam_grade = "No grade";
    }
    String StudentName(String Sname){
       Student_name = Sname;
       return Student_name;
    }
    String ExamName(String Ecode){
        //Return examination name according to code passed
        if(Ecode.equals("VB")){
            Exam_name = "Visual Basic .NET";
        
        }else if(Ecode.equals("JV")){
            Exam_name = "Java .NET";   
        
        }else if(Ecode.equals("PH")){
            Exam_name = "PHP";
        
        }else{
            Exam_name = "No Exam selected"; //Incase no code was entered
        }
        return Exam_name;
    }
}

In the above code, the method ExamName receives a two characters input representing the examination name.

Using IF … ELSE statement, it returns the full examination name representing the two characters input else it returns the string "No Exam selected".

In the Examination class i.e. the main class, add the code to pass the Examination two characters input (Ecode) and the output statement like shown below:

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-29

At this stage, run the main class again and this time you expect it to display the Student name and Examination name.

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-29

Just like what we have done with the ExamName method, we are going to add another method that will return the examination score. Add the following code in the ExamDetails class.

Java classes and methods

package examination;

public class ExamDetails {
    private String Student_name;
    private String Exam_name;
    private String Exam_score;
    private String Exam_grade;
    
    ExamDetails(){
       Student_name = "No name given";
       Exam_name = "unknown";
       Exam_score = "No score";
       Exam_grade = "No grade";
    }
    String StudentName(String Sname){
       Student_name = Sname;
       return Student_name;
    }
    String ExamName(String Ecode){
        //Return examination name according to code passed
        if(Ecode.equals("VB")){
            Exam_name = "Visual Basic .NET";
        
        }else if(Ecode.equals("JV")){
            Exam_name = "Java .NET";   
        
        }else if(Ecode.equals("PH")){
            Exam_name = "PHP";
        
        }else{
            Exam_name = "No Exam selected"; //Incase no code was entered
        }
        return Exam_name;
    }
    String ExamScore(int Escore){
        Exam_score = "Score: "+Escore + "%"; //Get score
        return Exam_score;
    }
}

The ExamScore method combines the score with strings “Score:“ and “%”. So if the value in Escore is 67, the text "Score: 67%" will be stored in the Exam_score field. In the Examination class i.e. the main class, add the code to pass the score (Escore) and the output statement like shown below. Run the program again to see the output.

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-29

Now for the final part, we are going to add another method that will return the examination grade according to the score attained. Add the following code in the ExamDetails class.

Java classes and methods

package examination;

public class ExamDetails {
    private String Student_name;
    private String Exam_name;
    private String Exam_score;
    private String Exam_grade;
    
    ExamDetails(){
       Student_name = "No name given";
       Exam_name = "unknown";
       Exam_score = "No score";
       Exam_grade = "No grade";
    }
    String StudentName(String Sname){
       Student_name = Sname;
       return Student_name;
    }
    String ExamName(String Ecode){
        //Return examination name according to code passed
        if(Ecode.equals("VB")){
            Exam_name = "Visual Basic .NET";
        
        }else if(Ecode.equals("JV")){
            Exam_name = "Java .NET";   
        
        }else if(Ecode.equals("PH")){
            Exam_name = "PHP";
        
        }else{
            Exam_name = "No Exam selected"; //Incase no code was entered
        }
        return Exam_name;
    }
    String ExamScore(int Escore){
        Exam_score = "Score: "+Escore + "%"; //Get score
        return Exam_score;
    }

    //Here we find grade
    String ExamGrade(int Escore){
        String grade = "";   
        if(Escore >=0 && Escore <= 35){
            grade = "FAIL";

        }else  if(Escore >=35 && Escore <= 50){
            grade = "PASS";

        }else  if(Escore >=50 && Escore <= 70){
            grade = "CREDIT";

        }else  if(Escore >=70 && Escore <= 100){
            grade = "DISTINCTION";

        }else{
            grade = "Score out of range";

        }
        return "Grade: "+grade;
    }
}

In the main class, add the code to pass the score and output the grade just like we did with the other methods. The complete main class i.e. Examination class should look like shown below. Run the main class and you should be able to get the Student name, Examination name, Score and Grade.

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-29

Sample Java problem with copy and paste solution code

Write a Java application which meets the following requirements:

In the application, you should declare a class called “Employee” with the following details:

Variables

Variable Name Description of variable

EmpNo

Employee Number

EName

Employee Name

EDesig

Employee Designation

BSal

Basic Salary

HA

House Allowance

Methods

Member Functions Description of Member Functions

getValues()

Should initialize the values for the member variables EmpNo, ENname, EDesig, BSal, HA

CalculateSalary()

Should calculate the Gross salary as the sum of the BSal and HA

DisplayValues()

Should print the value of the instance variables along with Gross salary

Requirements

  1. In your main method, create N number of Employee objects, where the value of N is obtained from the user and store the objects into an array.
  2. Use appropriate methods to read the values of the Employee objects from user, Calculate the Gross Salary for each Employee and print employee details and salary details of all objects created.
  3. Use exception handling appropriately.
  4. Use comments to illustrate the various concepts applied / utilized in the solution.
  5. Ensure the use of meaningful variable names, consistent indentation of program code


Java solution code for the above problem

/*
 * This program accepts salary details
 * of N number of employees, calculates gross salary
 * and print the final details on the console
 */
package employee;
import javax.swing.JOptionPane;
public class Employee {
    private int EmpNo; //Employee Number
    private String EName; //Employee name
    private String EDesig; //Employee designation
    private int BSal; //Basic salay
    private int HA; //House allowance
    private int GSal; //Gross salary
    
    Employee() { //Create Employee class constructor and set default values
        EmpNo = 0; 
        EName = "Unknown"; 
        EDesig = "Unknown";
        BSal = 0; 
        HA = 0; 
        GSal = 0;
}
  
   void getValues(){ //Initialize instance variables 
        EmpNo = Integer.parseInt(JOptionPane.showInputDialog("Enter employee number"));
        EName = JOptionPane.showInputDialog("Enter employee name");
        EDesig = JOptionPane.showInputDialog("Enter designation");
        BSal = Integer.parseInt(JOptionPane.showInputDialog("Enter basic salary"));
        HA = Integer.parseInt(JOptionPane.showInputDialog("Enter House allowance"));
    }
   int CalculateSalary(){ //Calculate basic salary
       GSal = BSal+HA;
       return GSal;
   }
   void DisplayValues(){ //Print values of the instance variables
       
       System.out.println("Employee nunber: "+EmpNo);
       System.out.println("Employee name: "+EName);
       System.out.println("Designation: "+EDesig);
       System.out.println("Basic salary: "+BSal);
       System.out.println("House allowance: "+HA);
       System.out.println("Gross salary: "+this.CalculateSalary());
   }
    public static void main(String[] args) {
      //Get N number of employees from the user
      int EmpNum = Integer.parseInt(JOptionPane.showInputDialog("Calculate salary for how many employees?"));
      Employee[] newEmp = new Employee[EmpNum];//Create array of N objects
      
      try { //Trap and handle errors if any
            for(int i = 0; i<newEmp.length; i++){
                 newEmp[i] = new Employee(); //Loop through the objects and for 
                 newEmp[i].getValues(); //every object, get employee details 
      }
      System.out.println("----------------------------------------------");
      System.out.println("EMPLOYEES SALARY DETAILS. TOTAL EMPLOYEES: "+EmpNum);
      
            for(int i = 0; i<newEmp.length; i++){
                System.out.println("----------------------------------------------");
                newEmp[i].DisplayValues(); //Loop through the objects and print details
            }
      }catch (Exception err ) {
            System.out.println(err.getMessage());//Throw error message if any
        }
     }
  }

Here is a Java problem for you to try

A parking garage charges $10 minimum fee to park for up to three hours. The garage charges an additional $2 per hour or part thereof in excess of three hours. The maximum charge for any given 24-hour period is $50. Assume that no car parks for longer than 24 hours at a time.

Write a Java application that calculates and displays the parking charges for each customer who parked in the garage the previous day. You should enter in a dialog box the hours parked for each customer. The program calculates and displays the running total of previous day’s receipts. The program should use the method calculateCharges() to determine the charge for each customer.

Well, that is all we have for Java classes but I would recommend that you practice more and look for more resources about Java classes and methods. Learn how to write more advanced Java classes and how to manipulate Java classes and methods. In the next lesson, we shall look at Java and Inheritance.

<< Lesson 28 | Lesson 30 >>

Want to make money online?

Comments

Danson Wachira (author) from Nairobi, Kenya on March 07, 2013:

Hi Paul,

Welcome and thanks for the visit and comment.

paul bernard on March 07, 2013:

u are awesome dude!! god bless u!

Danson Wachira (author) from Nairobi, Kenya on October 24, 2012:

Hi Nell Rose,

Thanks for that compliment and thanks for the visit and vote.

Nell Rose from England on October 23, 2012:

This I am sure is going to be so helpful to people who need this info, great work and voted up!

Danson Wachira (author) from Nairobi, Kenya on October 19, 2012:

Hi kashmir56,

The other fact about programming is that we use programmed devices everyday..iPhone, Computer, ATM, Tablets...so i would say programming is truly part of our life. Thanks for the visit and comment.

Thomas Silvia from Massachusetts on October 18, 2012:

Hi my friend, has i said before i know very little about programming, but this will be very helpful for those who may be just learning it. Well done !

Vote up and more !!! SHARING !

Danson Wachira (author) from Nairobi, Kenya on October 17, 2012:

Hi Lord De Cross,

I would not imagine how i would have completed my undergraduate studies if i didn't get a little push by researching on net, i guess this is my small way of paying back. Thanks for the visit and comment.

Joseph De Cross from New York on October 17, 2012:

Bringing the class to every corner of the world, who cannot afford a school or a teacher. Valuable indeed, and well written my friend. You are doing a favor to so many as I said before. Just keep them coming and the world will remember your effort! From machine language to C++, cyber intelligence is helping us to live better.

Related Articles