You are on page 1of 14

Manipal University Jaipur

First Semester 2017-18


Object-Oriented Programming Using Java [CS 1332]
LAB-3 [Class Design Basics - Part 1]
1. How to read user inputs in a typical java application?
1.1. Use of BufferedReader class for Reading User Inputs
1.2. Use of Scanner class for Reading User Inputs
2. How to design a simple class with proper Attribute(s) and Method(s)?
3. How to create an instance/object of a class and How to Access the
instance fields and methods via object references.

1. How to read user inputs in a typical java application?


There are two ways how you can read user inputs from the keyboard (referred by stdin in
C and System.in in Java).

First method is by using the instance of a class named java.io.BufferedReader and the
second method is by using the instance of a class named java.util.Scanner.

1.1 Using BufferedReader for text based user input from the keyboard The following
example will teach you how to read user inputs using BufferedReader class.

Type the following code in file named Example1.java and save it in your respective
work space.

// File Name : Example1.java


import java.io.*; // java.io package is to be imported
// for using BufferedReader class
class Example1
{
public static void main(String args[])
{
/* Step I */

// Instantiate InputStreamReader class and pass System.in


// [Default Input Stream] to its constructor

InputStreamReader isr = new InputStreamReader(System.in);

/* Step II */

/* Instantiate BufferedReader class and pass the reference


variable isr of type InputStreamReader created in

Object-Oriented Programming Using Java [Lab 3] Page. 1


the previous line to the constructor of
BufferedReader */

BufferedReader br = new BufferedReader(isr);

System.out.println("Enter Your First Name: ");

/* Step III */
/* Call readLine method on br reference variable which
is of type BufferedReader */

String name = br.readLine();


System.out.println("Your name is: " + name);
} // End of main
}// End of class Example1

Compile the above code and note down what type of errors you will get during
compilation.

In order to successfully compile the above file, you can adopt any of the following two
methods [ Note: We have not covered Exceptions in class so far. So as of now you have to
adopt the methods as it is.]

Method 1: Change the main() method line by appending throws IOException


[shown in red color]

class Example1
{
public static void main(String args[]) throws IOException
{
/* Step I */

// Instantiate InputStreamReader class and pass System.in


// [Default Input Stream] to its constructor

InputStreamReader isr = new InputStreamReader(System.in);

/* Step II */

/* Instantiate BufferedReader class and pass the reference


variable isr of type InputStreamReader created in
the previous line to the constructor of
BufferedReader */

BufferedReader br = new BufferedReader(isr);

System.out.println("Enter Your First Name: ");

Object-Oriented Programming Using Java [Lab 3] Page. 2


/* Step III */
/* Call readLine method on br reference variable which
is of type BufferedReader */

String name = br.readLine();


System.out.println("Your name is: " + name);
} // End of main
}// End of class Example1

Method 2: Put the call to readLine() method in try catch block. [As shown in red
color].

class Example1
{
public static void main(String args[])
{
/* Step I */

// Instantiate InputStreamReader class and pass System.in


// [Default Input Stream] to its constructor

InputStreamReader isr = new InputStreamReader(System.in);

/* Step II */

/* Instantiate BufferedReader class and pass the reference


variable isr of type InputStreamReader created in
the previous line to the constructor of
BufferedReader */

BufferedReader br = new BufferedReader(isr);

System.out.println("Enter Your First Name: ");

/* Step III */
/* Call readLine method on br reference variable which
is of type BufferedReader */

try
{
String name = br.readLine();
System.out.println("Your name is: " + name);
}
Catch(IOException ae) {}
} // End of main
}// End of class Example1

Object-Oriented Programming Using Java [Lab 3] Page. 3


The readLine() method of the BufferedReader class reads every type of input only in String
form. For example, if you are reading integer numbers then these numbers are read or are
made available in program only in String form. So, in program if you want to use the read
inputs in any form other than the String form then you have to parse the read input into its
respective type. For this purpose you can use certain parse() methods defined in various
library classes. Some important parse() methods are given below:

S.No Class Name Method Name Usage Usage-Examples


1 java.lang.Integer parseInt() Used to parse Integer.parseInt(10);
an integer Integer.parseInt(4);
type value
from a String
type
2 java.lang.Float parseFloat() Used to parse Float.parseFloat(4.5f);
a float type
value from a
String type
3 java.lang.Double parseDouble() Used to parse Double.parseDouble(4.5);
a double type
value from a
String type
4 java.lang.Short parseShort() Used to parse Short.parseShort(100);
a short type
value from a
String type
5 java.lang.Long parseLong() Used to parse Long.parseLong(10L);
a long type
value from a
String type
6 java.lang.Byte parseByte() Used to parse Byte.parseByte(10);
a byte type
value from a
String type
7 java.lang.Boolean parseBoolean() Used to parse Boolean.parseBoolean(true);
a boolean
type value
from a String
type

NOTE : All the parse() methods shown in the above table, executes/works without runtime
errors/exceptions if the string type value represents their exact type. For example, the
statement Integer.parseInt(10) executes successfully because 10 can be reliably
parsed into an integer type. On the other hand, the execution of the statement
Integer.parseInt(10.56) results in an runtime exception named
NumberFormatException. Some more examples about the use of parse methods are
given below:
Float.parseFloat(10.56f); Executes Successfully

Object-Oriented Programming Using Java [Lab 3] Page. 4


Float.parseFloat(10.56); Results in NumberFormatException
Boolean.parseBoolean(true) Executes Successfully
Boolean.parseBoolean(1) Results in NumberFormatException

Exercise 1 [To be Included in Lab File in Handwritten Form]

Write a program in java to take 10 integer numbers as user input using the
BufferedReader and print the sum of these numbers.

// File Name : Lab2Ex1.java


import java.io.*;
class Lab2Ex1
{
public static void main(String args[])
{
int number = 0;
int sum = 0;

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

// Note : The above statement can be bifurcated in two statements also as follows
// First Create an InputStreamReader instance using System.in
// InputStreamReader ins = new InputStreamReader(System.in);
// Create a BufferedReader instance br using InputStreamReader ins
// BufferedReader br = new BufferedReader(ins);

for(int i =0; i < 10; i++)


{
System.out.println( Please Enter + i + Number);
// Reads the Number using br instance field
number = Integer.parseInt(br.readLine());
sum += number;
}
System.out.println(Sum = + sum);
}// End of Method
}// End of class

Execute the above file for the following two cases and observe the output
1. Execute the file by giving ten inputs as [1 2 2 3 4 5 6 7 8 9] [ All Valid Integers]
2. Execute the file by giving ten inputs as [1 2 3 4.5 6 7 8 9 10 67] [ One Invalid
Input]

Exercise 2 [To be Included in Lab File in Handwritten Form]

Write a program in java which reads the values of five attributes related with a
student such as name (name of a student), age (age of a student), marks_in_phy
(marks in physics out of 100), marks_in_chem(marks in chemistry out of 100) and
marks_in_math(marks in mathematics out of 100). In the end program displays the

Object-Oriented Programming Using Java [Lab 3] Page. 5


average marks and final grade of the student. The final grade of the student is
computed as follows:
1. Final Grade = A++ if average marks >=90
2. Final Grade = A+ if average marks <90 but >= 80
3. Final Grade = A if average marks <80 but >= 70
4. Final Grade = B++ if average marks < 70 but >= 60
5. Final Grade = B+ if average marks <60 but >= 50
6. Final Grade = B if average marks <50 but >= 40
7. Final Grade = C if average marks < 40 but >=35
8. Final Grade = Fail if average marks < 35
An Incomplete Program is given below and you have to complete it.

// File Name : Lab2Ex2.java


import java.io.*;
class Lab2Ex2
{
public static void main(String args[])
{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String name = null ; // Name of Student


int age = 0; // Age of Student
double marks_in_phy=0.0; // Marks in Physics
double marks_in_chem=0.0; // Marks in Chemistry
double marks_in_maths=0.0; // Marks in Maths
double average_marks = 0.0 // Average Marks

String final_grade = null; // Final Grade of Student

// Use br instance to read the values of name, age,


// marks_in_phy, marks_in_chem, marks_in_maths variables

average_marks = (marks_in_phy + marks_in_chem + marks_in_maths) / 3.0;

if (average_marks >= 90.00)


final_grade = A++;
else

// Complete The Code

System.out.println( Name of Student : + name);


System.out.println( Age of Student : + age);
System.out.println( Marks in Physics : + marks_in_phy);
System.out.println( Marks in Chemistry : + marks_in_chem);
System.out.println( Marks in Maths : + marks_in_maths);
System.out.println( Average Marks : + average_marks);
System.out.println( Final Grade : + final_grade);
}// End of Method
}// End of class

Object-Oriented Programming Using Java [Lab 3] Page. 6


1.2 Using the Scanner class for text based user input from the keyboard

The latest version of Java especially that are introduced after JDK 1.5, supports user
input via class named java.util.Scanner. The use of this class is simple and overcomes
the difficulties that are encountered during the use of BufferedReader class.
Note that System.in is the default input stream supported in Java. Also remember that
System.out is the default output stream. In order to read input via Scanner class, you
have to first create an object/instance of type Scanner by passing the default input
stream System.in to it as follows

Scanner sc = new Scanner(System.in);


[Note: in the above statement you have created an instance named sc of type Scanner].
After creating a Scanner type instance, you can use various types of next() methods of
Scanner class to read an input of a particular type. Some important next() methods of
the Scanner class are mentioned below
1. String next() This method can be used if the input type is String.
2. boolean nextBoolean() This method can be used to read a boolean type value.
3. byte nextByte() This method can be used to read a byte type value.
4. double nextDouble() This method can be used to read a double type value..
5. float nextFloat() This method can be used to read a float type value.
6. int nextInt() This method can be used to read an int type value..
7. long nextLong() This method can be used to read a long type value.
8. short nextShort() This method can be used to read a short type value.

Note : If the type of the input value is not according to the type of the variable
then program generates a runtime exception named InputMismatchException.
For example, if an input value 10.5 is supplied for an int type variable then it
results in InputMismatchException during execution.

Type the following Java program in a file named Lab2Ex2.java.

// File Name : Lab2Ex2.java


Import java.util.Scanner; // import java.util package in
// order to use Scanner class
Class Lab2Ex2
{
public static void main(String args[])
{
//variable declaration
int num1; // An int type variable
double double1; // A double type variable
String numStr1, numStr2; // String type variables

/* Step 1 */
/* Create/Instantiate a scanner class instance by passing
System.in to its constructor */

Scanner in = new Scanner(System.in);

Object-Oriented Programming Using Java [Lab 3] Page. 7


System.out.println("Enter an integer: ");
// Use nextInt() Method of Scanner class to read an int type
num1 = in.nextInt();
System.out.println("You entered: " + num1);

System.out.println("Enter a double: ");


// Use nextDouble() Method of Scanner class to read a double
double1=in.nextDouble();
System.out.println("You entered: " + double1);

System.out.println("Enter your first name ");


// Use next() Method of Scanner class to read a String type
numStr1 = in.next();
System.out.println("Your name is " + numStr1);

System.out.println("Enter your surname");


numStr2 = in.nextLine();
System.out.println("Your surname is " + numStr2);

in.close(); // close the stream


}// End of main() method
}// End of class Lab2Ex2

Compile and run the above code and observe the output?

Exercise 3 and Exercise 4 [To be Included in Lab File in Handwritten Form]

Rewrite the Code given in Exercise 1 and 2 Using Scanner class and these
programs are to recorded in the Lab file in handwritten form.

Object-Oriented Programming Using Java [Lab 3] Page. 8


2. Class Design Basics

A class provides a template for defining the attributes (known as instance fields or object
variables in Java) and operations (known as functions in C++ and methods in Java). A
simple class template is shown below
class class-name
{
Instance Fields;
Instance Method;
}// End of class
A classs body is enclosed within a pair of curly braces {}.

Let us define a class named ComplexNumber. A complex number in mathematical terms is


represented as x + iy where x is known as real-part and y is known as an imaginary part.
Create a class named ComplexNumber as follows
The class has two attributes named real and imag . Scope of the attributes is private and
type is double.
Add two methods for reading the values of two attributes i.e. one method for reading the value
of real field and other method for reading the value of imag field.
Similarly, add two methods for setting/updating the values of the two named instance fields
Add a method for checking the equality of two complex number instances. Two complex
number instances are equal if the values of their real and imag fields are equal.
Add a method for adding two complex numbers. For example, suppose cn1 and cn2 are two
complex number instances. These instances can be added either via cn1.add(cn2) or
cn2.add(cn1).
Add a method for subtracting one complex number say cn1 from other say cn2. For example,
suppose cn1 and cn2 are two complex number instances. You should be able to subtract
cn1 from cn2 via cn2.sub(cn1). You should be able to subtract cn2 from cn1 via
cn1.sub(cn2).
Add a method for displaying the values of instance field

After defining the ComplexNumber class, wrtite a driver class named Lab2Ex3 which performs
the following tasks in sequential order:
Create an instance named cn1 of type ComplexNumber
Display the values of instance fields associated with cn1.
Set the value of real field of cn1 to 10.5
Set the value of imag field of cn1 to 20.5
Display the updated values of instance fields associated with cn1.
Create an instance named cn2 of type ComplexNumber
Set the value of real field of cn2 to 10.5

Object-Oriented Programming Using Java [Lab 3] Page. 9


Set the value of imag field of cn2 to 20.5
Call the equality method of ComplexNumber class to check whether cn1 and cn2 are
equal or not.

Type the following code in a file named ComplexNumberTest.java

// File Name ComplexNumberTest.java


class ComplexNumber
{
private double real; // Real Part
private double imag; // Imaginary Part

// Method to read/get/retrieve the value of Real Part


public double getReal() { return this.real; }
// Method to read/get/retrieve the value of Imaginary Part
public double getImag() { return this.imag; }
// Method to set/update the value of Real Part
public void setReal(double real) { this.real = real; }
// Method to set/update the value of Imaginary Part
public void setImag(double imag) { this.imag = imag; }

// Method to Check Equality of Two Complex Number Instances


public boolean isEqual(ComplexNumber other)
{
/*
This Method Checks the Equality of this parameter with
other parameter. Note that this is a Java keyword and always refers
to the instance field through which the method is invoked.
Two complex numbers are equal if their real and imaginary part values are
equal
*/

boolean b1 = this.real == other.real; // Check if real part values are equal


// The above statement can be written as boolean b1 = this.getReal() == other.getReal();
boolean b2 = this.imag == other.imag; // Check if imag part values are equal
// The above statement can be written as boolean b2 = this.getImag() == other.getImag();

return b1 && b2;


} // End of Method

Object-Oriented Programming Using Java [Lab 3] Page. 10


// Method to add two complex numbers
public ComplexNumber add(ComplexNumber other)
{
ComplexNumber cN = new ComplexNumber();
cN.setReal( this.getReal() + other.getReal());
cN.setImag(this.getImag() + other.getImag());
return cN;
} // End of Method
// Method to subtract two complex numbers
public ComplexNumber sub(ComplexNumber other)
{
ComplexNumber cN = new ComplexNumber();
cN.setReal( this.getReal() - other.getReal());
cN.setImag(this.getImag() - other.getImag());
return cN;
}// End of Method

// Method to display the details of a ComplexNumber Instance


public void display()
{
System.out.println( Real Part : + real);
System.out.println( Imaginary Part : + imag);
}// End of Method
}// End of class

// Driver class
class ComplexNumberTest
{
public static void main(String args[])
{
// Create a ComplexNumber instance named cn1
ComplexNumber cn1 = new ComplexNumber();

// Display the values of instance fields associated with cn1.


cn1.display();

//Set the value of real field of cn1 to 10.5


cn1.setReal(10.5);
//Set the value of imag field of cn1 to 20.5
cn1.setImag(20.5);
//Display the updated values of instance fields associated with cn1.
cn1.display();

// Create an instance named cn2 of type ComplexNumber

Object-Oriented Programming Using Java [Lab 3] Page. 11


ComplexNumber cn2 = new ComplexNumber();
// Set the value of real field of cn2 to 10.5
cn2.setReal(10.5);
// Set the value of imag field of cn2 to 20.5
cn2.setImag(20.5);
// Call the equality method of ComplexNumber class to check whether cn1
// and cn2 are equal or not.
boolean bb = cn1.isEqual(cn2);
System.out.println(bb);

ComplexNumber cn3 = cn1.add(cn2);


cn3.display();

ComplexNumber cn4 = cn1.sub(cn2); // cn1 cn2


cn4.display();

ComplexNumber cn5 = cn2.sub(cn1); // cn2 cn1


cn5.display();
}// End of Method
}// End of class ComplexNumberTest

Compile and Execute the Above Code and Observe the Output.

Exercise 5 [To be Included in Lab File in Handwritten Form]

Define a class named Point which encapsulates a point in 2-dimensional space. A point
p is represented by two co-ordinates name x (x-coordinate) and y (y-coordinate).
You have to define the class as per following specification

Add two attributes in class Point named x and y of type double and having
class scope
Add two methods for reading/getting the values of x and y fields
Add methods for setting/updating the values of x and y field
Add a method for checking the equality of any two Point type instances.
Suppose p1 and p2 are two Point type instances. They are equal iff the values
their x and y fields are equal
Add a method to compute the distance between two points.
Add a method to display the details of any point type instance.

Define a driver class named PointTest which performs the following tasks sequentially
Create two Point type instances named p1 and p2.
Display the details of p1 and p2
Update the values of x and y fields of instance p1 to 3.4 and 5.6 respectively

Object-Oriented Programming Using Java [Lab 3] Page. 12


Update the values of x and y fields of instance p2 to 13.4 and 15.6
respectively
Compute the distance between points p1 and p2

You are given an incomplete Java code of the above-mentioned two classes named Point
and PointTest. You have to complete as per the mentioned specification.

// File Name: Lab2Ex5.java


// Class Point
class Point
{
private double x;
private double y;

// Add a Method to get/read the value of x


public double getX() { /* Complete This Method */ }

// Add a Method to get/read the value of y

// Add a Method to set/update the value of x


public void setX(double x ) { /* Complete This Method */ }

// Add a Method to set/update the value of y


public void setY(double y ) { /* Complete This Method */ }

// Add a Method to Check The Equality of Two Point Type References


public boolean isEqual(Point other) { /* Complete This Method */ }

// Add a Method to Compute the Distance Between two Points


public double computeDistance(Point other)
{
// This method returns the distance between this and other references
// Distance between two points p1(x1,y1) and p2(x2,y2) is given as
// Square Root [ (y2-y1)2 + (x2-x1)2 ]
// Note : Use Math.sqrt() function to compute the square root of a number

// Complete This Method as per above-mentioned logic


}// End of Method

// Add a Method to display the details of any Point type reference


public void display()
{
// Complete This Method
}
} // End of class Point

Object-Oriented Programming Using Java [Lab 3] Page. 13


// Driver Class : PointTest
class PointTest
{
public static void main(String args[])
{
//Create two Point type instances named p1 and p2.

//Display the details of p1 and p2

//Update the values of x and y fields of instance p1 to 3.4 and 5.6 respectively

//Update the values of x and y fields of instance p2 to 13.4 and 15.6 respectively

//Compute the distance between points p1 and p2

}// End of Method


}// End of class PointTest

********* END OF LAB-3 **********

Object-Oriented Programming Using Java [Lab 3] Page. 14

You might also like