Exercises for the Java and HTML course (Beginners Course)
Common Programming Errors of Beginners
Problem 1.
The basic data types can be modified by access modifiers.
For example the keyword public
is an access modifier.
In Java, these access modifiers describe who can use the method.
The keyword public
means that any method in any
class that has access to an instance of the Error1
class can call the method.
The keyword static
is another access modifier.
Static variables and methods (member functions) in Java
are the same as static data members and member functions in C/C++.
The original purpose of static
in C/C++ was to denote
local variables that do not go away when the local scope is exited.
In that context, the term static indicates that the variable stays
around and is still there when the block is entered again.
The combination of the three access modifiers
public static final
is used for a global constant.
This global constant cannot be changed.
The error message is: can't assign a value to a final variable
// Error1.java
public class Error1
{
public static final int a = 92;
public static final int b = -87;
public static void main(String[] args)
{
a = a + b;
System.out.println(a);
}
}
Problem 2.
The left curly bracket {
stands for begin block
and the right curly bracket }
stands for end block. The problem
at the next program is that the variable b
goes out of scope. The error message is:
undefined variable b
// Error2.java
public class Error2
{
public static void main(String[] args)
{
int a = 7;
{
int b = 8;
}
int result = a + b;
System.out.println(result);
}
}
Problem 3.
We recall that Java is case sensitive.
To solve the problem with the next program,
have a look at the table of keywords.
The error message is:
Invalid expression statement
// Error3.java
public class Error3
{
public static void main(String args[])
{
int true = 1;
int false = 0;
int result = true*false;
System.out.println("The result is " + result);
}
}
Problem 4.
In Java the data types on the left and right hand sides of
=
must be the same.
Type conversion must be called explicitly.
The two error messages are:
Incompatible type of declaration.
Explicit cast needed to convert int to byte.
// Error4.java
public class Error4
{
public static void main(String[] args)
{
byte j = -128;
byte k = 127;
byte l = j + k;
System.out.println(l);
}
}
Problem 5.
What is the problem with the following code ?
It compiles and runs, but the output is
numbers are the same.
However, the numbers are not the same.
// Error5.java
public class Error5
{
public static void main(String[] args)
{
int i = -1281;
int j = 1280;
if(i == j);
System.out.println("numbers are the same");
}
}
Problem 6.
The following code gives the error message:
Incompatible type int to boolean. Can't convert int to boolean
What is the problem ? Fix it.
// Error6.java
public class Error6
{
public static void main(String[] args)
{
int i = -1280;
int j = -1280;
if(i = j)
System.out.println("numbers are the same");
}
}
Problem 7.
The following program compiles and runs, but the output is:
wrong values sum = -1
However the output should only be:
sum = -1.
// Error7.java
public class Error7
{
public static void main(String[] args)
{
int n = 2;
int sum = 0;
switch(n)
{
case 1:
sum++;
break;
case 2:
sum--;
default:
System.out.println("wrong values ");
break;
}
System.out.println("sum = " + sum);
}
}
Problem 8.
Java clearly distinguishes between
basic data types and abstract data types which are
objects. The error message is:
no method machting addElement(double) found in Vector
However, there is a method addElement
in the Vector class.
// Error8.java
import java.util.*;
public class Error8
{
public static void main(String[] args)
{
Vector w = new Vector(4);
double x = 3.14;
char c = 'Z';
int k = -50;
w.addElement(x);
w.addElement(c);
w.addElement(k);
double y = w.elementAt(0);
System.out.println(y);
char d = w.elementAt(1);
System.out.println(d);
int m = w.elementAt(2);
System.out.println(m);
}
}
Problem 9.
Every basic data type has a wrapper class, for example char -> Character
The error message is: incompatible type of declaration
The question is how to convert basic data types
(such as char
) to abstract data types
(such as Character
).
// Error9.java
public class Error9
{
public static void main(String[] args)
{
Character Ch = 'A';
System.out.println(Ch);
Character X = new Character('a');
System.out.println(X);
char x = X;
System.out.println(x);
}
}
Pitfalls for Beginners in Java
Problem 1.
What is the output of the following program?
Surprisingly for the beginner it is not 9223372036854775808.
Explain why.
// Pitt1.java
public class Pitt1
{
public static void main(String[] args)
{
long a = 9223372036854775807L;
long b = 1L;
long result = a + b;
System.out.println(result);
}
}
Problem 2.
As in C++, the left shift operator is
given by <<
and the right shift operator is given
by >>
. What is the output of the following program ?
Notice that 2 (decimal) in binary is 10b.
Furthermore notice that the data type int
is signed and 32 bits long. What is the output of the following program ?
// Pitt2.java
public class Pitt2
{
public static void main(String[] args)
{
int a = 2;
int b = a << 30;
System.out.println(b);
int c = a << 31;
System.out.println(c);
int d = a << 32;
System.out.println(d);
}
}
Problem 3.
The following program compiles without any
problem. However when we run the program it goes on forever.
Explain why.
// Pitt3.java
public class Pitt3
{
public static int f1(int x) { return 2*f2(x); }
public static int f2(int y) { return 3*f3(y); }
public static int f3(int z) { return 4*f1(z); }
public static void main(String[] args)
{
int a = 6;
int result = f3(a);
System.out.println(result); // =>
}
}
Problem 4.
To compare whether strings are equal we
use the method equals
in the String class.
Can we also use ==
? What is the output of the program ?
// Pitt4.java
public class Pitt4
{
public static void main(String[] args)
{
String s1 = "ABC";
String s2 = "ABD";
if(s1 == s2)
System.out.println(s1);
else
System.out.println(s2);
boolean bool = s1.equals(s2);
System.out.println(bool);
}
}
Problem 5.
The output of the following program
is that The letter C is the same
although C and D differ.
// Pitt5.java
public class Pitt5
{
public static void main(String[] args)
{
String s1 = new String("ABC");
String s2 = new String("ABD");
for(int i=0;i < 3;i++)
{
if (s1.charAt(i) == s2.charAt(i));
{
System.out.println("The letter " + s1.charAt(i) + " is the same");
}
}
}
}
Problem 6.
In C++ we can use references or pointers to swap two
basic data types, for examples two integers.
How can we translate the following C++ program
into Java ? The problem is that in Java we cannot pass
basic data types by reference.
// Pitt6.java
#include <iostream.h
>
void swap(int& a,int& b)
{
int temp = a;
a = b; b = temp;
}
void main()
{
int x = 7;
int y = -4;
swap(x,y);
cout << "x = " << x << endl; // => 4
cout << "y = " << y << endl; // => 7
}
Problem 7.
Surprisingly for C++ programmers the following code
compiles and runs under Java.
However, there is a big problem with this code.
Explain why. Look at the output. Fix the problem.
// Pitt7.java
public class Pitt7
{
public static void main(String args[])
{
double x[] = { 2.2, 4.5, 3.1 };
double y[] = { 4.1, 5.6, -8.9 };
y = x;
for(int i=0; i < y.length; i++)
{
System.out.println("y[" + i + "] = " + y[i]);
}
x[0] = -17.4;
for(int i=0; i < y.length; i++)
{
System.out.println("y[" + i + "] = " + y[i]);
}
}
}
Programming Assignment
Problem 1.
Write a Java application using two for
loops to produce the following pattern
of asterisks.
*
**
***
****
*****
******
*******
********
Can this problem be solved with one for
loop?
Problem 2.
Write an applet that displays a rectangle and a line.
The line should intersect the rectangle at two
opposite corners.
Hints. Obviously we use the
void paint(Graphics g)
method (function) from the Component
class.
To draw the rectangle and the line we use
the methods
drawRect(int,int,int,int)
and
drawLine(int,int,int,int)
which are in the Graphics
class.
Problem 3.
Read in three integers of data type long
from the keyboard. Then add the three numbers.
Type convert the sum to data type double
and divide by 3.0 (data type double
)
to find the arithmetic mean.
Problem 4.
From version 1.1 Java includes a class BigInteger
to handle verylong integers. Write a Java program that
creates two verylong integers, for example 8912345678 and
-7892033234567 and then subtract and divide the two numbers.
Convert the first verylong integer into a double
.
Then display the result on the screen.
Hints. Select the proper constructor. The constructor you should use is
BigInteger(String str)
which translates the decimal String
representation
of a BigInteger
into a BigInteger.
The method to subtract the verylong numbers is
BigInteger subtract(BigInteger val)
The method to divide the verylong numbers is
BigInteger divide(BigInteger val)
The method to convert from a BigInteger
to a double
is
double doubleValue()
Do not forget to import the BigInteger
class
( java.math.BigInteger
).
We recall that in Java we cannot overload operators
such as +, -, *, /, %
as we can in C++.
Problem 5.
Write and run a Java program that enters an 8-digit string
for a birthdate from the keyboard. The first two digits
in the string are the month of birth, the
next two are the day and the remaining four are
the year. The Java program should squeeze out these
substrings and display it on the screen as follows:
month of birth:
day of birth:
year of birth:
Hint. Use the String class and the method
public String substring(int beginIndex,int endIndex)
Try to add exception handling for the case
if the month and day are out of range.
Problem 6.
The following Java program compiles and runs. However, when you try
to close the window it will not close. Under MS Windows use
Crt+Alt+Del and End Task to kill the process.
Under LINUX you have to kill the process.
Fix the program so that you can close the window.
// MyFrame.java
//
// A frame is a window that has a title bar, a menu bar, a border,
// a cursor, and an icon image. Frame windows are the standard objects
// used for drawing graphics.
//
// Java uses the keyword super to refer to members of the parent class.
// super(s) invokes the constructor in the Frame class
//
// public Frame(String title)
// constructs a new, initially invisible Frame object with the
// specified title.
import java.awt.Frame;
import java.awt.Button;
class ButtonFrame extends Frame
{
Button b;
ButtonFrame(String s)
{
super(s);
setSize(200,100);
setLocation(400,50);
b = new Button("Click me!");
add(b);
setVisible(true);
}
}
class MyFrame
{
public static void main(String[] args)
{
ButtonFrame buttonFrame = new ButtonFrame("MyFrame");
}
}
Problem 7.
Write a text file counter.dat
which contains the integer 0.
Then write a Java application that reads this file
and increments the integer by one. Then the new
integer is written back to the file counter.dat
.
This means every time we open and close the file
the integer number is incremented by 1.
Problem 8.
The following Applet simulates a digital clock.
The Applet compiles and runs, but the
output is only:
0 : 0 : 0
Explain why. Fix the problem.
To what values are the basic data types initialized ?
// Clock.java
import java.applet.Applet;
import java.awt.*;
import java.util.Calendar;
// The Runnable interface should be implemented by any class
// whose instance are intended to be executed by a thread.
public class Clock extends Applet implements Runnable
{
Thread thread;
Font font = new Font("Monospaced", Font.BOLD, 64);
int hour, minute, second;
// Applet class: called by the browser or appletviewer
// to inform this applet that it has been loaded into the system
public void init()
{
if(thread == null)
{
thread = new Thread();
thread.start();
}
}
// override the run() method from Thread class
public void run()
{
for(;;) // forever
{
Calendar time = Calendar.getInstance();
hour = time.get(Calendar.HOUR);
minute = time.get(Calendar.MINUTE);
second = time.get(Calendar.SECOND);
repaint(500); // request re-drawing every 500 milliseconds
try { Thread.sleep(500); } catch(Exception e) { }
}
}
public void paint(Graphics g)
{
g.setFont(font);
String time = String.valueOf(hour)
+ ":" + String.valueOf(minute)
+ ":" + String.valueOf(second);
g.drawString(time, 50, 50);
}
}
Projects
Project 1.
Write a class SoccerLeague.
The soccer league has 8 teams with
the names:
"PinkSocks", "WoundedKnee",
"FlatFoot", "LameDogs",
"NoScore", "UnReal",
"WetPants", "Grasshoppers".
The names of the teams should be
stored in a file teams.dat.
The method setupMatches
creates all
the matches (4 for each weekend) for the 7 weekends.
Of course each team plays exactly once against
each other team.
All the matches should be stored in a data file
setup.dat.
At each weekend the four
matches should be retrieved from the data
base and the results filled into the data file
setup.dat.
Then a method showTable
should calculate
the points (3 for a win, 1 for a draw,
and 0 for a loss) and put into the file
teams.dat.
Then the ranking table should be
displayed with the proper ranking for each row.
Number of the ranking,
the name of the team,
number of matches played,
the number of points,
number of goals scored,
number of goals received.
If the number of points are the same then
the goal difference should be used for the
ranking. If this is also the same the team
with more goals should be placed higher.
For example after 2 weekends the table
could be
1 FlatFoot 2 6 9 2
2 WoundedKnee 2 4 6 3
3 LameDogs 2 4 4 1
...........
Project 2.
Write a Java program with a class Rational to do
mathematics with rational numbers.
The class Rational should include the method
add
for adding two rational numbers
and a method multiply
to multiply two rational numbers.
The underlying data type should be long
.
Can you modify the code so that the data type
BigInteger
can be used ?
Project 3.
Rewrite the following code using the abstract data type
BigInteger.
This means int i; int n; int d
and the number 1000 must be replaced by BigInteger.
The methods in class BigInteger
we can use are:
add, equals, mod, compareTo
int compareTo(BigInteger val)
returns -1, 0, 1 as this BigInteger is numerically
less than, equal to, or greater than val.
Fields in the class BigInteger
are
static BigInteger ONE
static BigInteger ZERO
There is not method sqrt
in class BigInteger.
But somehow we can use
BigInteger pow(int exponent)
// TestPrime.java
public class TestPrime
{
public static void main(String [] args)
{
for(int i=0; i < 1000; i++)
{
if(isPrime(i))
System.out.print(i + " ");
}
} // end main
static boolean isPrime(int n)
{
if(n < 2) return false;
if(n == 2) return true;
if(n%2 == 0) return false;
for(int d=3; d < Math.sqrt(n); d += 2)
if(n%d == 0) return false;
return true;
} // end isPrime
}
Project 4.
Write a Java application that implements the
TV show "Who wants to be a millionare''.
Project 5.
Rewrite the program ButtonGame.java
on page 100 using the Swing components, i.e.
JButton, JPanel, JTextField
etc.