Monday, July 26, 2010

Java Practice


Here I've compiled a few Java beginner level exercises to practice with. At the end of the post are also links to other pages with beginner level exercises. I will continue to add on more as I progress in my studies.

Level: Beginner

Focus: Basic concepts, runtime errors

Here’s a piece of code that has been saved in a file called "JollyMessage.java":

// A jolly message is written to the screen!
class Jollymessage
{

public static void main(String[] args) {

//Write the message to the terminal window
System.out.println("Ho Ho Ho!");

}
}

The above code will produce a runtime error message. To put it another way, a mistake has been made but it won’t be picked up when the program is compiled, only when it is run. What is the mistake and what error will be returned when the compiled code is executed?


* * * * * * *



Focus: Wrapper Classes, Primitive Data Types
Playing With Wrappers Question


Every primitive data type has a corresponding wrapper class. These classes are handy if you need to make the primitive data type into an object. However, it's important to remember that the wrapper classes are not the same as primitive data types and will act differently in certain circumstances.

In the following lines of code I've been playing with wrapper classes. The question is can you figure out what the values of the wrapper objects will be?

Boolean eminem = new Boolean("yes");

Boolean lLCoolJ = new Boolean("true");

Integer mosDef = new Integer(Integer.MAX_VALUE+1);

Long queenLatifah = new Long(Integer.MAX_VALUE+1);

Long iceCube = new Long((long)Integer.MAX_VALUE + 1);

Long jayZ = new Long(iceCube++);

Long kanyeWest = new Long(++iceCube);

Character snoopDogg = new Character("c".replace("c", "d").toCharArray()[0]);

Double theGame = new Double(Double.POSITIVE_INFINITY);

Double common = new Double (Math.round(Double.POSITIVE_INFINITY));

Integer nas = 10444;
Integer trickTrick = 10444;
Boolean lilWayne = (nas == trickTrick);

Boolean bowWow = (nas.equals(trickTrick));



* * * * * * *



Focus: Loops, Wrapper Classes, Condition Statements, Converting Strings

String Conversion Question


This programming question is all about converting Strings to numbers. The Double and Integer wrapper objects both have methods that are capable of converting a String value and you will need to employ those methods to produce the correct results.

Write a Java program that

* inputs a String from a user. Expect the String to be a series of numbers each separated by a space (e.g., "11 2 36.4 4 8.9 7.6 3 256").
* converts the String into the series of numbers that it represents.
* adds the numbers together.
* displays the result to the user.

To make things a little more interesting allow for the String to include octal and hexadecimal literals (e.g., "11 2 0xEF 36.4 4 8.9 0647 7.6 3 256").

To test the program calculate the total for the following String: "56.7 0.8 345 0xEFF 8.99 126 0647 73 5.67".



* * * * * * *



Focus: Loops
Counting Rabbits Question


In a Fibonacci sequence each number is the sum of the previous two numbers (i.e., it starts with 0,1,1,2,3,5,8 and continues on). The sequence is the result of Fibonacci's attempt in 1202 to find out how many rabbits you get after a certain number of generations. Each number represents how many pairs of rabbits there would be when they are breeding under ideal circumstances. The task is to write a program that calculates and displays the first 22 numbers of a Fibonacci sequence.

Your code will display Fibonacci's hypothesis for 20 generations of rabbits (the first two numbers represent the start of the population and the maturing of the first pair of rabbits).




* * * * * * *



Focus: Loops, Break Statement
Breaking Out Question


The focus of this programming question is on jumping out of loops. Almost always it's possible to write loops without the need for a break statement but sometimes it's convenient to do so. The following program does not contain examples of well written loops or ones that need a break statement. It's purpose is to get you thinking about how the break statement changes the logical flow of the code:

public class BreakingLoop {

public static void main(String[] args) {

int count = 0;
loop_one:
for (int k=5;k < 100;k++)
{
for (int j=3; j < 100; j++)
{
if (j % 2 == 0)
{
break;
}
if (k == 67)
{
break loop_one;
}
count ++;
}
}
System.out.println(count);
}
}


There are two break statements in the program, one with a label and one without. The question is for each break statement what is the next line to be executed and what is the final total of the variable count?




* * * * * * *




Focus: Binary Numbers, Bitwise Operators, Formatting Numbers
Shifting Bits Question


This programming exercise is a test of your skills at formatting binary numbers combined with using bitwise operators.

Bitwise operators interact directly with the underlying bits of a number. For example, the number 16 is the binary equivalent of 10000. The binary shift operators can be used to shift the bit pattern of a number either to the right (i.e., use the >> operator) or to the left (i.e., use the << operator). So,

int bitShift = 16;
bitShift = bitShift >> 1;

will shift the binary pattern 10000 of 16 one place to the right. The new bit pattern 1000 means the value of the variable bitShift is now 8.

The task is to write is an interactive bit shifter. The program must accept a binary number written as a String. It should then display the value of the number in denary and its binary pattern, followed by a menu of options. The menu should allow the user to:

1. Shift bits to the right
2. Shift bits to the left
3. Stop shifting

If the user picks option 1 or 2 the corresponding bit shift should occur on the number. The new value and bit pattern should be displayed to the user followed by the menu. Option 3 should stop the program. To make things a little more interesting the bit pattern must be displayed as an 8 bit number (i.e., the binary number 101 should be formatted to have 5 leading zeros 00000101).

To test the program, use the binary number 1011 as the starting value and perform one bit shift to the right followed by four bit shifts to the left. What is the final denary value and bit pattern?



* * * * * * *



Focus: Logic, Arrays, Methods
Odd Magic Square Question


I'm not really sure who first came up with a magic square. There is a story about a huge flood in China a long time ago. The people were worried they would be washed away and tried to appease the river god by making sacrifices. Nothing seemed to work until a child noticed a turtle sporting a magic square on its back that kept circling the sacrifice. The square told the people how big their sacrifice needed to be in order to save themselves. Since then magic squares have been the height of fashion for any discerning turtle.

In case you've never come across one before, a magic square is an arrangement of sequential numbers in a square so that the rows, columns and diagonals all add up to the same number. For instance, a 3x3 magic square is:

8 1 6
3 5 7
4 9 2


Each row, column and diagonal adds up to 15.

This programming exercise is concerned with creating odd sized magic squares (i.e., the size of the square can only be an odd number, 3x3, 5x5, 7x7, 9x9, and so on). The trick with making such a square is to place the number 1 in the first row and middle column. To find where to place the next number, move diagonally upwards to the right (i.e., one row up, one column across). If such a move means you fall off the square, wrap around to the row or column on the opposite side. Finally, if the move takes you to a square that is already filled, go back to the original square and move downwards by one. Repeat the process until all the squares are filled.

For example, a 3x3 magic square would start like so:

0 1 0
0 0 0
0 0 0


A move diagonally upwards means we wrap around to the bottom of the square:

0 1 0
0 0 0
0 0 2


Likewise the next diagonal move upwards means we wrap around to the first column:

0 1 0
3 0 0
0 0 2


Now the diagonal move upwards results in a square that is already filled, so we go back to where we came from and drop down a row:

0 1 0
3 0 0
4 0 2


and it continues on and on until all the squares are full.
Program Requirements:

* a user must be able to enter in the size of the magic square.
* they must only be allowed to enter in an odd number.
* use a method to create the magic square.
* use a method to display the magic square.

The question is can your program create a 5x5 magic square like the one below?

17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9


Hint: Apart from the programming aspects of this exercise it's also a test of logic. Take each step of creating the magic square in turn and figure how it can be done with a two dimensional array.




* * * * * * *







* * * * * * *



http://blog.tmorris.net/beginner-java-exercise-with-data-types/

http://www.home.hs-karlsruhe.de/~pach0003/informatik_1/aufgaben/en/java.html

http://www.javacoffeebreak.com/books/extracts/javanotesv3/c11/exercises.html



0 comments: