Sie sind auf Seite 1von 13

OOP (JAVA) Practical Questions (Example Codes)

Question 1 :public class Q1 { public static void main(String[] args) { Q1 q1=new Q1(); // We are instructed to call each method in the main method. Main method is a static method and all other methods are non-static methods. In java non-static method or variable cannot be called inside a static method directly. So, the solution for that is calling to those methods through an object. So, here we are creating an object of this class itself. double numbers[]={34.5,56.7,12.6,98.4,54.21,89.55,54.2,98.4,73.2,21.45,34.5,98.4,21.45,98.4,9.3};//defin ing an array to store the numbers. There are various types of java arrays. In this type we can define an array without a length. array type is double since the data are decimal/double values q1.total(numbers); //The method 'total' needs the data inside the array. So, we pass the array value from this code. At the same time we call that method to be executed. q1.minAndmax(numbers);//we call to the method 'minAndMax'. Also pass the array values from main method to 'minAndMax'. q1.maximumAppearance(numbers); //we call to the method 'maximumAppearance'. } private void total(double numberArray[]){//Method to find the total of array elements. parameter list contain an array called 'numberArray' to store the value which are passed from the main method at the time of method calling. double arrayTotal=0; //variable to store the total for(int count=0;count<15;count++){ //loop to add elements of the array of local array named 'numberArray' arrayTotal=arrayTotal+numberArray[count]; //variable 'count' is changing. So, we can choose each and every element and add. } System.out.println(arrayTotal); //print the total average(arrayTotal); //method 'average' needs the total value of the array to count the average. So we pass it from here at the same time of calling the array. } private void average(double total){ System.out.println(total/15); //array length is known as 15. If the array length is changing, find the java method to automatically get the array length. } private void minAndmax(double numberArray[]){ double min=numberArray[0]; double max=numberArray[0];//At the defining time of the variables relate with situations like this, it is safe to assign the first array element as the initial values of the variables. Because default value 0 may not in your array element list.

for(int count=0;count<15;count++){ //Finds the minimum element if(min>numberArray[count]){ min=numberArray[count]; } } for(int count=0;count<15;count++){ //finds the maximum element if(max<numberArray[count]){ max=numberArray[count]; } } System.out.println("Maximun ="+max); System.out.println("Minimum ="+min); } private void maximumAppearance(double numberArray[]){ //finds the maximumly occured value in the array. double appearingNumber=0; int times=0; double finalAppearingNumber=0; int finalTimes=0; for(int count=0;count<15;count++){ times=0; appearingNumber=numberArray[count]; for(int count1=0;count1<15;count1++){ if(appearingNumber==numberArray[count1]){ times++; } } if(finalTimes<times){ finalTimes=times; finalAppearingNumber=appearingNumber; } } System.out.println("Maximumly appearing number ="+finalAppearingNumber); } }

Question 2://relate with the Athlete.java public class Q2 { double speedSet[]=new double[3]; //Another array type which should be given a length at the definition. String identificationNo[]=new String[3]; public static void main(String[] args) { Q2 q2=new Q2(); Athlete athlete1=new Athlete(); //Since we are adviced to input data about three athlete, we may face to a difficulty of typing the same data set in the Athlete class for three times. But with OOP concepts we can create objects with an one class. Athlete class is the mold for an one athlete. Athlete athlete2=new Athlete();//create the second athlete from the same class od Athlete Athlete athlete3=new Athlete();//create the third athlete from the same class od Athlete athlete1.getTimes();//calls the method called getTimes in the object of athlete1 which was created using the Athlete class. It gets the input for first athlete. q2.speedSet[0]=athlete1.speed;// put the value in the speed variable in the object which was created from class Athlete to the array of speedSet in this class. 'speedSet' is a class, non-static array so we have to call it through an object of this class itself.(because this method is static) q2.identificationNo[0]=athlete1.identificationNo; athlete2.getTimes();//calls the method called getTimes in the object of athlete2 which was created using the Athlete class. It gets the input for second athlete. q2.speedSet[1]=athlete2.speed; q2.identificationNo[1]=athlete2.identificationNo; athlete3.getTimes(); q2.speedSet[2]=athlete3.speed; q2.identificationNo[2]=athlete3.identificationNo; q2.highestSpeed();// call a non-static mehtod in this class itself. } public void highestSpeed(){// Identify the highest speed or the winner of the game double highestSpeed=this.speedSet[0]; String highestSpeedPlayerIdentificationNo=this.identificationNo[0]; for(int count=0;count<3;count++){ if(highestSpeed<this.speedSet[count]){ highestSpeedPlayerIdentificationNo=this.identificationNo[count]; highestSpeed=this.speedSet[count]; } } System.out.println("The Winner is ="+ highestSpeedPlayerIdentificationNo); System.out.println("The minimum time is ="+ highestSpeed); } }

import java.util.Scanner;// Scanner class is used. So, we have to import it first. public class Athlete { double speed=0; String identificationNo=""; public void getTimes(){ Scanner sc=new Scanner(System.in); //create an object of the Scanner class to get the input from the user. System.out.println("Enter the Identification Number....."); this.identificationNo=sc.nextLine();//get the String type inputs from the user System.out.println("Starting Hour....."); int startHour=sc.nextInt();//get the int type inputs from the user System.out.println("Starting Minute....."); int startMin=sc.nextInt(); System.out.println("Starting Second....."); int startSec=sc.nextInt(); System.out.println("Ending Hour....."); int endHour=sc.nextInt(); System.out.println("Ending Minute....."); int endMin=sc.nextInt(); System.out.println("Ending second....."); int endSec=sc.nextInt(); calculateSpentTimes(startHour,startMin,startSec,endHour,endMin,endSec,this.identification No);//pass these values to the method 'calculateSpentTimes' to calculate the time spent. } public void calculateSpentTimes(int startHour,int startMin,int startSec,int endHour,int endMin,int endSec,String IdentificationNo){ double spentSeconds=((endHour-startHour)*3600)+((endMin-startSec)*60)+(endSecstartSec);//calculate the consumed time calSpeed(spentSeconds,IdentificationNo); } public void calSpeed(double time,String identificationNo){ this.speed=100/time; //calculates the speed. 100m is given in the question. time is from the above method. System.out.println("Speed of the Player "+identificationNo+" ="+this.speed); //speed is a class variable. To call to a class variable(outside of all methods. These type of variables can be accessed from any method in the same class) we use this. } }

Question 03 :public abstract class Player { // This is a abstract class. Cannot create objects from this. But can be extended. (According to the question this is the parent class) String name=""; String contactAddress=""; String tpNumber=""; String status=""; abstract void calAverage(); //This is how an abstract method is defined. No body just the return type and name(method signature) @Override //In java there is an inbuilt abstract method called 'toString'. Here we have overriden it. This method can out put the name of the current class. public String toString() { return super.toString(); } public static void main(String[] args) { Bastman bastman=new Bastman(2000, 5); //Input data to the constructor of the object bastman initially. bastman.name="Namal"; bastman.contactAddress="Kandy"; bastman.tpNumber="yyyyyyyyyyy"; bastman.status="Good"; bastman.calAverage(); bastman.info(); System.out.println(bastman.toString()); //call to the to string method of the bastman object of the Bastman class Bowler bowler=new Bowler(300, 5); bowler.name="Kumara"; bowler.contactAddress="Matale"; bowler.tpNumber="xxxxxxxxxx"; bowler.status="Nice"; bowler.calAverage(); bowler.info(); System.out.println(bowler.toString()); } }

// Another child class of the Player class public class Bowler extends Player { private int totalWickets; private int totalNoOfMatches; Bowler(int totalWickets,int totalNoOfMatches){ this.totalWickets=totalWickets; this.totalNoOfMatches=totalNoOfMatches; } @Override void calAverage() { System.out.println("Average Wickets ="+this.totalWickets/this.totalNoOfMatches);//calAverage() calculates the average wickets here. But see how it is working in class Bowler. } @Override public String toString() { return super.toString(); } public void info(){ System.out.println(this.name); System.out.println(this.contactAddress); System.out.println(this.tpNumber); System.out.println(this.status); } }

public class Bastman extends Player{ //This is a child class. It is inhereted from the parent class called Player. private int totalRuns; //Private variables cannot be accessed by outer classes private int noOfOneDayMatches; Bastman(int totalRuns,int noOfOneDayMatches){ //This is a constructor of this class. Since we need to input data to private variables from the player class, we get those data through this constructor. Player class pass the data to this constructor directly. this.totalRuns=totalRuns; //This is the place where private variables are replaced by the values which are received from the Player class. this.noOfOneDayMatches=noOfOneDayMatches; } @Override //override or specify the action of the abstract method "calAverage". This was defined at the Player class. Now we override it here. void calAverage() { System.out.println("Average runs ="+this.totalRuns/this.noOfOneDayMatches); // calAverage() calculates the average runs here. But see how it is working in class Bowler. } @Override public String toString() { return super.toString(); } public void info(){ System.out.println(this.name); //variable 'name' is not implement in this class. Then how it is be here ? 'name, contactAddress, tpNumber,status' are defined at the 'Player' or parent class. We extended it to this class. As a result of that we can use those variables as they are in this class. System.out.println(this.contactAddress); System.out.println(this.tpNumber); System.out.println(this.status); } }

Question 4 :import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; public class Q4 { public static void main(String[] args) { Q4 Q4=new Q4(); Q4.mainLogging(); } public void mainLogging(){ Scanner sc=new Scanner(System.in); String stuID=""; String stuPWD=""; //Logging form System.out.println("------------Log In----------"); System.out.println("Enter Student ID :"); stuID=sc.nextLine(); System.out.println("Enter Password :"); stuPWD=sc.nextLine(); validation(stuID,stuPWD); } public void validation(String stuID,String stuPWD){ try {//In a file operation in java we have to use try/catch to handle errors. String stuIdFile=""; String stuPWDFile=""; String stuNameFile=""; Scanner fileScanner=new Scanner(new File("stuDetails.txt")); //Logging to the text file at the same folder where .java file is located. while(fileScanner.hasNext()){ //Read the while until the last word //Read three words at the same time and stores at the variables.(Reads password, user name, name in an one record ) stuIdFile=fileScanner.next(); stuPWDFile=fileScanner.next(); stuNameFile=fileScanner.next(); if(stuIdFile.equals(stuID) && stuPWDFile.equals(stuPWD)){//verify the password and the user name against the user input data.

System.out.println("You are welcome...."+stuNameFile); System.exit(1); // Here we exit the program (if verified) } } System.out.println("Wrong Password......."); mainLogging(); // This is used to restart the program after an unauthorized logging. } catch (FileNotFoundException ex) { Logger.getLogger(Q4.class.getName()).log(Level.SEVERE, null, ex); } } }

Das könnte Ihnen auch gefallen