Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Exercises

1. Write a program to keep inputting integer values until –1 is entered.


2. Write a program using a while loop to display a message 10 times. Each message
should be on a separate line using the following format with numbering starting from
1: A message
2: A message
3: A message
……
3. Write a program that inputs the radius of a circle and displays its circumference and
area. (use Math.PI for π)
4. Write a program to read in a line of text as a String and output the number of
characters and words it contains. Spaces and tabs should not be counted as characters.
5. Write a program that reads a decimal integer and prints out its binary equivalent.
6. Write a program that counts the number of times a specified character appears in a line
of text.
7. Write a program that uses a recursive method to calculate the product of a sequence of
numbers specified by the user. For example, if the user specifies 4 to 8, the method
calculates 4*5*6*7*8.
8. Write a method to test if an integer of type long is a prime number. The method should
return a boolean.
9. Write a program to read in 10 integers and store them in an array. Then display the
contents of the array.
10. Write a program to read in a sequence of integers until ‘stop’ is entered. Store the
integers in an array. Then display the average of the numbers entered.
11. A matrix can be represented using a 2D array. Write methods to perform matrix
addition, subtraction and multiplication. Each method should take two 2D arrays as a
parameter and return a new 2D array containing the result. Use the methods in a test
program to verify that they work correctly.
12. Write a program to act as a simple address book, storing names and addresses in a data
file.
13. Create an implementation of the interface Queue that throws exceptions appropriately.
Declare any exception classes needed and write a test class

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING
1
Exercise 1: (Complex numbers)
The purpose of this exercise is to define a class “CN” so that it can be used to
manipulate complex numbers.

Part A
Follow the specification below to define the class CN:
1. Attributes
CN contains two attributes “re” and “im” representing respectively the real and
imaginary parts of the complex number.

2. Constructors
CN contains a no-argument constructor (it sets re and im to zero), and a 2-argument
constructor having as parameters initial values of real and imaginary parts of the
complex number.

3. Methods
• getRe: returns the real part of the complex number.
• getImg: returns the imaginary part of the complex number.
• setRel and setImg: respectively modify the value of real and imaginary parts.
• add, multiply and subtract: to add, multiply or subtract two complex numbers.
• getModule: return the module of an instance of CN
• equals: Tests if two complex numbers are equal.(2 complex numbers are equal if
their real and imaginary parts are the same)
• clone: returns a copy of an instance of CN (the new copy will not share the same
reference with the original one).

Part B
Propose now a class TestCN with the main method to illustrate how to use the class CN
defined above.

Exercise 2:
Consider three classes A, B, and C. Assume that:
• B extends A, B and C implement the interface I,

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING
2
• B overrides the method meth() of A,
• and B and C define a method fonc() of the interface I
For instructions (on the block S1) below, specify which version of method “meth” or “fonc”
is called.
S1
A a; B b; C c; I i;
a = new A();
a = b;
b = new B();
a.meth(); (3)
c = new C();

i = b; i.fonc(); (4)
a.meth(); (1)
i = c; i.fonc(); (5)
b.meth(); (2)

Exercise 3: (Control flow)


1. Write a java program that reads a positive integer n, calculate and displays its
factorial.
2. Suppose now that the value of n is passed as argument to the main function. Write a
java program that prints out n!.

Exercise 4: (Method random() of java.math.Math ) ***


Write a program that simulates rolling a pair of dice. You can simulate rolling one die
by choosing one of the integers 1, 2, 3, 4, 5, or 6 at random. The number you pick represents
the number on the die after it is rolled (Use the method random of java.math.Math. For

example, int n = (int)(Math.random()*6)+1 returns a random interger between 1


and 6).
You can assign this value to a variable to represent one of the dice that are being
rolled. Do this twice and add the results together to get the total roll. Your program should
report the number showing on each die as well as the total roll.

For example:
The first die comes up 3
The second die comes up 5

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING
3
Your total roll is 8

Exercise 5:
Write a program that asks the user’s name, and then greets the user by name. Before
outputting the user’s name, convert it to upper case letters. For example, if the user’s
name is Fred, then the program should respond “Hello, FRED, nice to meet you!”.

Exercise 6: (StringTonizer) **
Write a program that reads one line of input text and breaks it up into words. The words
should be output one per line. Assume that words are separated by the blank character “ ”. For
example, if the user inputs the line “Hello Word! I am a student”, the program prints:
Hello
Word!
I
am
a
student

Exercise 7:
Suppose that a file contains information about sales figures for a company in various cities.
Each line of the file contains a city name, followed by a colon (:) followed by the data for that
city. The data is a number of type double. However, for some cities, no data was available. In
these lines, the data is replaced by a comment explaining why the data is missing. For
example, several lines from the file might look like:
San Francisco: 19887.32
Chicago: no report received
New York: 298734.12
Write a program that will compute and print the total sales from all the cities together. The
program should also report the number of cities for which data was not available.
The name of the file is “sales.dat”.

What output is produced by the following program segment? (Recall that name.charAt(i)is
the i-th character in the string, name.)

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING
4
String name;
int i;
boolean startWord;
name = "Richard M. Nixon";
startWord = true;
for (i = 0; i < name.length(); i++) {
if (startWord)
System.out.println(name.charAt(i));
if (name.charAt(i) == ’ ’)
startWord = true;
else
startWord = false;
}

Exercise 8:
To “capitalize” a string means to change the first letter of each word in the string to upper
case (if it is not already upper case). For example, a capitalized version of “Now is the time to
act!” is “Now Is The Time To Act!”. Write a subroutine named printCapitalized that will
print a capitalized version of a string to standard output. The string to be printed should be a
parameter to the subroutine. Test your subroutine with a main() routine that gets a line of
input from the user and applies the subroutine to it. Note that a letter is the first letter of a
word if it is not immediately preceded in the string by another letter. Recall that there is a
standard boolean-valued function Character.isLetter(char) that can be used to test whether its
parameter is a letter. There is another standard char-valued function,
Character.toUpperCase(char), that returns a capitalized version of the single character passed
to it as a parameter. That is, if the parameter is a letter, it returns the upper-case version. If the
parameter is not a letter, it just returns a copy of the parameter.

Exercise 9

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING
5
1. Define a class named Point, with two attributes x and y representing its coordinates. The
constructor of class Point takes as parameters, initial values of x and y (Point(int x_init, int
y_init). Its methods are described below:
- move(int dx, int dy) : this method adds dx to x and dy to y
- display() : Displays the point coordinates (x and y)
2. Suppose that your program must also manipulate colored points represented by a class
named PointCol Describes as follow:
- Class PointCol extends Point and has only one attribute color (representing the color
of its instances).
- Its constructor signature is PointCol(int x_init, int y_init, byte color).
- PointCol overrides the methods display() of its super class, to show its coordinates
and color .
Propose a definition of class PointCol.

3. Consider class TestPoint defined by:


Class TestPoint{
public static void main(String arg[]){
Point p = new Point(3, 2);
p.display(); (a)

PointCol pc = new PointCol(5, 5, (byte)3);


p = pc;
p.display(); (b)
}
}

What output is produced by instructions (a) and (b)?

Exercise 10:
The hexadecimal digits are the ordinary, base-10 digits ’0’through ’9’ plus the letters ’A’
through ’F’. In the hexadecimal system, these digits represent the values 0 through 15,
respectively. Write a function named hexValue that uses a switch statement to find the
hexadecimal value of a given character. The character is a parameter to the function, and its
hexadecimal value is the return value of the function. You should count lower case letters ’a’

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING
6
through ’f’ as having the same value as the corresponding upper case letters. If the parameter
is not one of the legal hexadecimal digits, return -1 as the value of the function.

Exercise 11: ***


Write a program that displays a window containing a button labeled “Say Hello”. When the
user clicks on that button, the program displays the message “Hello World”.

Exercise 12:
Implement a program with this interface:

Clicking the buttons increments or decrements the displayed counter value.

Exercise 13:
Write a Swing program to display this window:

When the button is clicked, the text typed into the JTextField at the top of the window is
copied into the label in the middle of the window.

Exercise 14:
Implement a calculator program (using GUI)

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING
7
Solutions

Exercise 1:
Part A
public class CN { //method substract
private double re; public CN subtract(CN c){
private double img; return new CN(re - c.re, img - c.img);
}
//No-argument constructor //method multiply
public CN(){ public CN multiply(CN c){
re = 0; return new CN(re*c.re + img*c.img,
img = 0; re*c.img + img*c.re);
} }
//2-arguments constructor
public CN(double re, double img){ //method getModule
this.re = re; public double getModule(){
this.img = img; return Math.sqrt(re*re + img*img);
} }

//Getter and Setter public boolean equals(CN c){


public double getRe(){ if((re == c.re) && (img == c.img))
return re; return true;
} else
public double getImg(){ return false;
return img; }
}
public void setRe(double re){ public CN clone(){
this.re = re; return new CN(re, img);
} }
public void setImg(double img){ }
this.img = img;
}
//method add
public CN add(CN c){
return new CN(re + c.re, img + c.img);
}

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING
8
Part B
public class TestCN {
public static void main(String arg[]){
CN c1 = new CN(0.5, 0.5);
CN c2 = new CN(1.5, 0.5 );
CN add = c1.add(c2);
CN sub = c2.subtract(c1);
System.out.println("c1 + c2 = "+add.getRe()+"+"+add.getImg()+"i");
System.out.println("c1 + c2 = "+sub.getRe()+"+"+sub.getImg()+"i");
}
}

Exercise 2
(1) This instruction calls the method “meth” of class A.
(2) This instruction calls the method “meth” of class B.
(3) It calls the method “meth” of class B.

(4) The method “fonc” of class B is called


(5) The method “fonc” of class C is called

Exercise 9
1. Class Point
class Point
{ private int x, y ;
public Point (int x, int y)
{
this.x = x ; this.y = y ;
}
public void move(int dx, int dy)
{
x += dx ; y += dy ;
}
public void display()
{
System.out.println ("my position is " + x + " " + y) ;
}
}

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING
9
2. Class PointCol
class Pointcol extends Point
{
private byte color ;
public Pointcol (int x, int y, byte color)
{
super (x, y) ; // must be the first instruction since the no-argument contrustor isn’t defined in
// the super class
this.color = color ;
}
public void display()
{
super. display() ;
System.out.print ("and my color is: " + color) ;
}
}

3. Instruction (a) will display:


my position is 3 2

(b) will display:


my position is 5 5
and my color is 3

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING
10

You might also like