3 – Loops (Level 3)

1 Sample Code

1.1 for Loop

public class ForLoop
{
    public static void main (String args [])
    {
        for (int i = 1; i <6; i++)
        System.out.println(i);
    }
}

1.2 while Loop

public class  WhileLoop
{
    public static void main (String args [])
    {
        int count = 1;
        while(count < 6)
        {
            System.out.println(count);
            count++;
        }
    }
}

1.3 do while Loop

import java.util.Scanner;
public class DoWhile
{
    public static void main (String args [])
    {
        Scanner scan = new Scanner(System.in);
        do
        {
            System.out.println("Are we there yet?");
        }while(!scan.nextLine().equals("yes"));
        System.out.println("Good!");
    }
}

2 Exercises

  1. Use a for loop to print the 5 times table up to 12 x 5
  2. Use a for loop to print the 7 times table up to 12 x 7 in the form “3 x 7 = 21”
  3. Use a for loop to print the following sequence: 0.5, 0.4, 0.3, 0.2, 0.1, 0
  4. Use a for loop to print the following sequence: 0.03, 0.02, 0.01, 0, -0.01, -0.02, -0,03
  5. Use a for loop to print five random numbers between 1 and 10
  6. Use a for loop to print the first ten square numbers: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
  7. Use a for loop to print the first ten triangle numbers: 1, 3, 6, 10, 15, 21, 28, 36,45, 55
  8. Use a while loop to print the numbers from 1 to 10 inclusive
  9. Use a while loop to print the sequence 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1
  10. Use a while loop to print the 4 times table up to 12 x 4.
  11. Use a while loop to print the 9 times table up to 12 x 9 in the form “1 x 9 = 9, 2 x 9=18… “
  12. Prompt the user to enter a number. Keep a running total of the numbers entered. Loop until the user enters -1, exit the loop and print the total
  13. Prompt the user to enter a number. Keep a running total of the numbers entered. Loop until the user enters -1, exit the loop and print the average
  14. Write a program to test if 91 is prime. Use a while loop to divide 91 by the numbers from 2 to 10. Output True if none of the numbers 91%(number) = 0 for any of the numbers, output False otherwise.
  15. Write a program to test if any number is prime. Use a while loop to divide the input by the numbers from 2 to sqrt(input). Output “Prime” if the number is prime, “Not Prime” otherwise.
  16. Use a while loop to print the sequence 1, -2, 3, -4, 5, -6, 7, -8
  17. Use a while loop to calculate pi using the Liebniz formula pi/4 = 1 – 1/3 + 1/5 – 1/7 + 1/9 – … How many iterations do you need to get 3.141?

2 – Selection Answers

1) Prompt the user as follows: “What’s the capital of France?” Output “Correct” if they enter “Paris”, output “Incorrect” otherwise

Scanner scan = new Scanner(System.in);
System.out.println("What's the capital of France?");
String ans = scan.nextLine();
if(ans.equalsIgnoreCase("Paris"))
{
    System.out.println("Correct");
}
else
{
    System.out.println("Incorrect");
}

2) Prompt the user as follows: “Name a month that starts with the letter A”: Output “Correct” if they enter “April” or “August”, output “Incorrect” otherwise

Scanner scan = new Scanner(System.in);
System.out.println("Name a month that starts with the letter A");
String ans = scan.nextLine();
if(ans.equalsIgnoreCase("April")||ans.equalsIgnoreCase("August"))
{
    System.out.println("Correct");
}
else
{
    System.out.println("Incorrect");
}

3) Prompt the user as follows: “Name a Beatle”. Output “Correct” if they enter “John”, “Paul”, “George” or “Ringo”, output “Incorrect” otherwise

Scanner scan = new Scanner(System.in);
System.out.println("Name a Beatle");
String ans = scan.nextLine();
if(ans.matches("John|Paul|George|Ringo"))
{
    System.out.println("Correct");
}
else
{
    System.out.println("Incorrect");
}

4) An online whisky shop charges for shipping as follows: One bottle, £5.99; two to five bottles, £7; more than five bottles, free. Prompt the user to enter the number of bottles bought and output the shipping cost.

Scanner scan = new Scanner(System.in);
System.out.println("Number bottles purchased:");
int number = scan.nextInt();
if(number == 1)
{
    System.out.println("Shipping £5.99");
}
else if (number <=5)
{
    System.out.println("Shipping £7");
}
else
{
    System.out.println("Shipping Free");
}

5) An online bookshop charges shipping as follows: Orders less than £10, £2.99; orders £10 and over, free; add on £2.50 for all orders if next day delivery is selected. Prompt the user to enter the cost of the order, and then prompt for next day delivery. Output the shipping cost.

Scanner scan = new Scanner(System.in);
System.out.println("Next Day Delivery (y/n)?");
String del = scan.nextLine();
System.out.println("Input order Cost:");
double cost = scan.nextDouble();
double shipping = 0;
shipping = cost < 10 ? 2.99 : 0;
if(del.equals("y"))
{
    shipping += 2.50;
}
System.out.println("Cost of shipping: £" + shipping);

6) Prompt the user to enter a number. Output if the number is odd or even.

Scanner scan = new Scanner(System.in);
System.out.println("Input Number:");
int number = scan.nextInt();
if(number % 2 == 0)
{
    System.out.println("even");
}
else
{
    System.out.println("odd");
}

7) Prompt the user to enter a number. Output Fizz if the number is divisible by 3, otherwise just output the number

Scanner scan = new Scanner(System.in);
System.out.println("Input Number:");
int number = scan.nextInt();
if(number % 3 == 0)
{
    System.out.println("Fizz");
}
else
{
    System.out.println(number);
}

8) Extend yesterday’s problem so that the computer will output Fizz if the number is divisible by 3, output Buzz if the number is divisible by 5 and otherwise just output the number.

Scanner scan = new Scanner(System.in);
System.out.println("Input Number:");
int number = scan.nextInt();
if(number % 3 == 0)
{
    System.out.println("Fizz");
}
else if(number % 5 == 0)
{
    System.out.println("Buzz");
}
else
{
    System.out.println(number);
}

9) Now extend yesterday’s problem further so that the computer will output Fizz if the number is divisible by 3, output Buzz if the number is divisible by 5, output Fizz Buzz if the number is divisible by both 5 and 3 and otherwise just output the number.

Scanner scan = new Scanner(System.in);
System.out.println("Input Number:");
int number = scan.nextInt();
if(number % 3 == 0 && number % 5 ==0)
{
    System.out.println("Fizz Buzz");
}
else if(number % 3 == 0)
{
    System.out.println("Fizz");
}
else if(number % 5 == 0)
{
    System.out.println("Buzz");
}
else
{
    System.out.println(number);
}

2 – Selection (Level 2)

1 Sample Code

1.1 Simple Selection

System.out.println("Enter your surname");
Scanner scan = new Scanner(System.in);
String surname = scan.next();
System.out.println("Are you M or F?");
String sex = scan.next();
if(sex.equals("M"))
{
    System.out.println("Hello Mr " + surname);
}
else
{
    System.out.println("Hello Ms " + surname);
}

1.2 Operators

public class  div37
{
    public static void main (String args [])
    {
        int x = 21;
        if (x%3 == 0 & x%7 == 0)
            {
                System.out.println("Number divisible by 3 and 7");
            }
    }
}

2 Exercises

  1. Prompt the user as follows: “What’s the capital of France?” Output “Correct” if they enter “Paris”, output “Incorrect” otherwise
  2. Prompt the user as follows: “Name a month that starts with the letter A”: Output “Correct” if they enter “April” or “August”, output “Incorrect” otherwise
  3. Prompt the user as follows: “Name a Beatle”. Output “Correct” if they enter “John”, “Paul”, “George” or “Ringo”, output “Incorrect” otherwise
  4. An online whisky shop charges for shipping as follows: One bottle, £5.99; two to five bottles, £7; more than five bottles, free. Prompt the user to enter the number of bottles bought and output the shipping cost.
  5. An online bookshop charges shipping as follows: Orders less than £10, £2.99; orders £10 and over, free; add on £2.50 for all orders if next day delivery is selected. Prompt the user to enter the cost of the order, and then prompt for next day delivery. Output the shipping cost.
  6. Prompt the user to enter a number. Output if the number is odd or even.
  7. Prompt the user to enter a number. Output Fizz if the number is divisible by 3, otherwise just output the number
  8. Extend yesterday’s problem so that the computer will output Fizz if the number is divisible by 3, output Buzz if the number is divisible by 5 and otherwise just output the number.
  9. Now extend yesterday’s problem further so that the computer will output Fizz if the number is divisible by 3, output Buzz if the number is divisible by 5, output Fizz Buzz if the number is divisible by both 5 and 3 and otherwise just output the number.

1 – Input and Output Answers

 1) Use the \t escape character to print out a noughts and crosses grid, as shown below in fig. 1
System.out.println("|\to\t|\t \t|\tx\t|");
System.out.println("|\t \t|\tx\t|\to\t|");
System.out.println("|\to\t|\tx\t|\to\t|");

2) Prompt the user to enter their (name). Print out “Hello” (name) “I hope you’re well”

Scanner scan = new Scanner(System.in);
System.out.println("Enter your name");
String name = scan.nextLine();
System.out.println("Hello " + name + ". I hope you're well.");

3) Use Math.sqrt() to print out the square root of 20

System.out.println(Math.sqrt(20));

4) Use Math.sqrt() to print out the square root of 20 to 2 decimal places

double root = Math.round(Math.sqrt(20)*100)/100d;
System.out.println(root);

5) Use Math.random() to print out a random integer between 5 and 10

System.out.println((int)(Math.random()*5)+5);

6) Use Math.pow() to print out 2 to the power of 8

System.out.println(Math.pow(2,8));

7) Prompt the user to enter a (number). Print out “The square root of ” (number) ” is ” (answer)

Scanner scan = new Scanner(System.in);
System.out.println("Emter a number");
double num = scan.nextDouble();
System.out.println("The square root of " + num + " is " + Math.sqrt(num));

or

Scanner scan = new Scanner(System.in);
System.out.println("Emter a number");
double num = scan.nextDouble();
System.out.format("The square root of %f is %f%n", num, Math.sqrt(num));

8) Prompt the user to enter two numbers. Print out the average of those numbers.

Scanner scan = new Scanner(System.in);
System.out.println("Emter a number");
double num1 = scan.nextDouble();
System.out.println("Enter another number");
double num2 = scan.nextDouble();
double average = (num1 + num2)/2;
System.out.println("The average of " + num1 + " and " + num2 + " is " + average);

9) To work out your BMI, divide your weight in kilograms by your height in metres squared. In other words BMI = w / h*h. Write a program that prompts the user to input their weight and height, and then outputs their BMI.

Scanner scan = new Scanner(System.in);
System.out.println("Emter your weight in kilograms");
double weight = scan.nextDouble();
System.out.println("Enter your height in meters");
double height = scan.nextDouble();
double BMI = weight/(height*height);
System.out.println("Your BMI is " + BMI);

1 Input and Output (Level 1)

Sample Code

 Escape Characters

Escape Sequence Character
\n newline
\t tab
\b backspace
\” double quote
\’ single quote
\\ backslash
\uDDDD Unicode character
public class uni
{
    public static void main (String args [])
    {
        System.out.println("\u0041");
    }
}

Simple Scanner

import java.util.Scanner;
public class Simpscan
{
    public static void main (String args [])
    {
        System.out.println("Enter your name");
        Scanner scan = new Scanner(System.in);
        String s = scan.next();
        System.out.println("Hello " + s);
    }
}

System.out.format

double pi = 3.1415;
System.out.format("Pi is %f to 4 d.p.%n", pi);

#+RESULTS

Pi is 3.141500 to 4 d.p.

Exercise

  1. Use the \t escape character to print out a noughts and crosses grid, as shown below in fig. 1
  2. Prompt the user to enter their (name). Print out “Hello” (name) “I hope you’re well”
  3. Use Math.sqrt() to print out the square root of 20
  4. Use Math.sqrt() to print out the square root of 20 to 2 decimal places
  5. Use Math.random() to print out a random integer between 5 and 10
  6. Use Math.pow() to print out 2 to the power of 8
  7. Prompt the user to enter a (number). Print out “The square root of ” (number) ” is ” (answer)
  8. Prompt the user to enter two numbers. Print out the average of those numbers.
  9. To work out your BMI, divide your weight in kilograms by your height in metres squared. In other words BMI = w / h*h. Write a program that prompts the user to input their weight and height, and then outputs their BMI.
Table 1: fig. 1
o x
x o
o x o

The Daily Java

Background

A couple of years ago I started to write the 99 Java Problems based on a loose copy of the Ninety-Nine Lisp Problems, which were themselves translations of Ninety-Nine Prolog Problems. I intended the problems to be a study aid for my students, however it quickly became apparent that many of the problems were too hard. I thus set about working on a more basic set of questions: the Daily Java is the result.

Why the Daily Java?

A few years ago the Maths Department in my school began what they called “The Daily Dose”. 16-18 year old students were required to complete 20 minutes of maths problems a day. This regular practice  proved very successful at raising attainment.
The Daily Java is based on this idea. It consists of a levelled set of questions in an ascending order of difficulty. Students can attempt more than one question a day, particularly at the beginning where the questions are easier, however, it is better to do little and often than to attempt to complete a big block all at once.

A Levelled Approach

The Daily Java questions are levelled. It’s my experience that nearly all students are capable of coding at level 1. Some students need help to progress to subsequent levels.
The following are based on my department’s experience in teaching coding. You may disagree with the levels, you may wish to use them as a starting point for further development, either way, I’d be very interested to hear your opinion.

Level 1

  • Output Strings and numbers
  • Concatenate Strings and numbers
  • Use variables
  • Perform simple arithmetic operations
  • Prompt for user input

Level 2

  • Use if statements with Strings
  • Use if statements with numbers
  • Use if else statements
  • Understand difference between addition and concatenation.

Level 3

  • for, while and do while loops
  • 1D Arrays
  • Concise comments

Level 4

  • Boolean operators AND OR NOT
  • Counts and iterations while loops
  • Nest if statements

Level 5

  • Nest for, while and do while loops
  • Methods and parameters
  • 2D Arrays
  • Variable scope

Level 6

  • Recursion
  • Modular programming
  • Self-documenting code: high level commenting

– Strings, Arrays and Collections Solutions

6 Strings Arrays and Collections Solutions

6.1 Print 2D Array

The following code creates a 3 x 3 tic-tac-toe grid filled with Xs.

 1: void tictactoe()
 2:    {
 3:       String [][] grid = new String[3][3];
 4: 
 5:       for(int i = 0; i<grid.length; i++)
 6:       {
 7: 	  for (int j = 0; j<grid.length; j++)
 8: 	  {
 9: 	      grid[i][j] = "X";
10: 	  }
11:       }
12:       printArray(grid);
13: 
14:    }

Write a method that will print a 2D array of any size. Test it using the 3 x 3 tic-tac-toe grid given above

6.1.1 Solution

 1: public class NNStringArray {
 2: 
 3:     NNStringArray()
 4:     {
 5: 	tictactoe();
 6:     }
 7: 
 8: 
 9:     void tictactoe()
10:     {
11:        String [][] grid = new String[3][3];
12: 
13:        for(int i = 0; i<grid.length; i++)
14:        {
15: 	   for (int j = 0; j<grid.length; j++)
16: 	   {
17: 	       grid[i][j] = "X";
18: 	   }
19:        }
20:        printArray(grid);
21: 
22:     }
23: 
24:     void printArray(String [][] grid)
25:     {
26: 	for(int i = 0; i<grid.length; i++)
27: 	{
28: 	    for(int j = 0; j<grid.length; j++)
29: 	    {
30: 		System.out.print(" | " + grid[i][j]);
31: 	    }
32: 	    System.out.println(" | ");
33: 	}
34:     }
35: 
36:     public static void main(String[] args) {
37: 	// TODO code application logic here
38: 	new NNStringArray();
39:     }
40: }

6.2 Chess Board

Create an 8 x 8 Array to represent a chess board. Print out the array with alternate ‘X’ and ‘O’ entries as shown in the example:

6.2.1 Solution

 1: public class NNStringArray {
 2: 
 3:     NNStringArray()
 4:     {
 5: 	chess();
 6:     }
 7: 
 8:     void printArray(String [][] grid)
 9:     {
10: 	for(int i = 0; i<grid.length; i++)
11: 	{
12: 	    for(int j = 0; j<grid.length; j++)
13: 	    {
14: 		System.out.print(" | " + grid[i][j]);
15: 	    }
16: 	    System.out.println(" | ");
17: 	}
18:     }
19: 
20:     void chess()
21:     {
22:        String [][] grid = new String[8][8];
23:        boolean fill = true;
24: 
25:        for(int i = 0; i<grid.length; i++)
26:        {
27: 	   for (int j = 0; j<grid.length; j++)
28: 	   {
29: 	       grid[i][j] = fill ? "X" : "O";
30: 	       fill = !fill;
31: 	   }
32: 	   fill = !fill;
33:        }
34:        printArray(grid);
35:     }
36: 
37:     public static void main(String[] args) {
38: 	// TODO code application logic here
39: 	new NNStringArray();
40:     }
41: }

6.3 Digits to Words

Write a method that will convert digits into words

6.3.1 Solution

 1: public class NNStringArray {
 2: 
 3:     NNStringArray()
 4:     {
 5: 	System.out.println(digitsToWords("35001922"));
 6:     }
 7: 
 8:     String digitsToWords(String s)
 9:     {
10: 	String words = "";
11: 	String [] digits = {"Oh","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
12: 
13: 	for (int i = 0; i<s.length();i++)
14: 	{
15: 	    int number = Integer.parseInt(s.substring(i,i+1));
16: 	    words = words + digits[number] + " ";
17: 	}
18: 
19: 	return words;
20:     }
21:     public static void main(String[] args) {
22: 	// TODO code application logic here
23: 	new NNStringArray();
24:     }
25: }

6.4 Time to Words

Write a method that will convert time to words. For example, 4:10 is “Ten past four” and 4:55 is “Five to Five”

6.4.1 Solution

 1: public class NNStringArray {
 2: 
 3:     NNStringArray()
 4:     {
 5: 	System.out.println(timeToWords("2:05"));
 6: 	System.out.println(timeToWords("2:47"));
 7: 	System.out.println(timeToWords("12:00"));
 8: 	System.out.println(timeToWords("2:00"));
 9: 	System.out.println(timeToWords("12:30"));
10: 	System.out.println(timeToWords("4:29"));
11: 	System.out.println(timeToWords("7:25"));
12: 	System.out.println(timeToWords("12:45"));
13: 	System.out.println(timeToWords("12:55"));
14:     }
15: 
16:     String timeToWords(String s)
17:     {
18: 	String time = "";
19: 	String [] input = s.split(":");
20: 
21: 	String [] times = {"o'clock","one","two","three","four", "five", "six",
22: 		"seven","eight","nine","ten","eleven","twelve","thirteen","fourteen",
23: 		"quarter","sixteen","seventeen","eighteen","nineteen","twenty",
24: 		"twenty one","twenty two","twenty three","twenty four",
25: 		"twenty five","twenty six","twenty seven","twenty eight",
26: 		"twenty nine","half past"};
27: 
28:        int hours = Integer.parseInt(input[0]);
29:        int minutes = Integer.parseInt(input[1]);
30: 
31:        //Watch out for e.g. 12:50 = Ten to One
32:        String sayMinutesp = minutes%5 != 0 ? " minutes" : "";
33:        if (hours  == 12 && minutes > 30) hours = 1;
34: 
35:        if (minutes == 0)
36:        {
37: 	     time = times[hours] + " o'clock";
38:        }
39:        else if (minutes == 15)
40:        {
41: 	   time = "Quarter past " + times[hours];
42:        }
43:        else if (minutes == 45)
44:        {
45: 	   time = "Quarter to " + times[hours];
46:        }
47:        else if (minutes>30)
48:        {
49: 	   time = times[60-minutes]+ sayMinutesp +  " to " + times[hours];
50:        }
51:        else
52:        {
53: 	   time = times[minutes] + sayMinutesp + " past " + times[hours];
54:        }
55: 
56: 	return time;
57:     }
58: 
59:     public static void main(String[] args) {
60: 	// TODO code application logic here
61: 	new NNStringArray();
62:     }
63: }

6.5 Morse Code Arrays

Write a program using arrays that translates plain text into morse code.

A B C D E F G
.- -… -.-. -.. . ..-. –.
H I J K L M
…. .. .— -.- .-..
N O P Q R S T
-. .–. –.- .-.
U V W X Y Z
..- …- .– -..- -.– __..

6.5.1 Solution

 1: public class NNStringArray {
 2: 
 3:     NNStringArray()
 4:     {
 5: 	System.out.println(morse("I never saw a purple cow"));
 6:     }
 7: 
 8:     String morse(String s)
 9:     {
10: 	s = s.toLowerCase();
11: 	String cipherText = "";
12: 	String code [] = {".-","-...","-.-.","-..",".","..-.","--.", "....",
13: 	    "..", ".---","-.-",".-..","--","-.","---",".--.","--.-",".-.",
14: 	    "...","-","..-","...-",".--","-..-","-.--","--..", "/"};
15: 
16: 	for (int i = 0; i<s.length(); i++)
17: 	{
18: 	    int number = s.charAt(i) == ' ' ? 26 : s.charAt(i)-97;
19: 	    cipherText = cipherText + code[number] + " ";
20: 	}
21: 
22: 	return cipherText;
23:     }
24:     public static void main(String[] args) {
25: 	// TODO code application logic here
26: 	new NNStringArray();
27:     }
28: }

6.6 Demorse Code Arrays

Now write a program using arrays that translates morse back to plain text.

6.6.1 Solution

 1: public class NNStringArray {
 2: 
 3:     NNStringArray()
 4:     {
 5: 	System.out.println(demorse(".. / -. . ...- . .-. / ... .- .-- / .- / .--. ..- .-. .--. .-.. . / -.-. --- .--"));
 6:     }
 7: 
 8:     String demorse(String s)
 9:     {
10: 	s = s.toLowerCase();
11: 	String cipher = "";
12: 	String code [] = {".-","-...","-.-.","-..",".","..-.","--.", "....",
13: 	    "..", ".---","-.-",".-..","--","-.","---",".--.","--.-",".-.",
14: 	    "...","-","..-","...-",".--","-..-","-.--","--..", "/"};
15: 
16: 	String [] letters = s.split("\\s+");
17: 	String plainText= "";
18: 
19: 
20: 	for (int i = 0; i<letters.length;i++)
21: 	{
22: 	    String letter = letters[i].trim();
23: 	    if (letter.equals("/"))
24: 	    {
25: 		plainText = plainText + " ";
26: 	    }
27: 	    else
28: 	    {
29: 		String decode = "";
30: 		for(int j = 0; j <code.length; j++)
31: 		{
32: 		    if (letter.equals(code[j]))
33: 		    {
34: 			char c = (char)(j+97);
35: 			plainText = plainText + Character.toString(c);
36: 		    }
37: 		}
38: 	    }
39: 	}
40: 
41: 	return plainText;
42:     }
43: 
44:     public static void main(String[] args) {
45: 	// TODO code application logic here
46: 	new NNStringArray();
47:     }
48: }

6.7 Morse Code Hashmap

Rewrite the Morse Code program using Hashmap

6.7.1 Solution

 1: import java.util.HashMap;
 2: import java.util.Map;
 3: import java.util.Map.Entry;
 4: 
 5: public class NNStringArray {
 6: 
 7:     Map <String, String> morse = new HashMap<String, String>();
 8: 
 9:     NNStringArray()
10:     {
11: 	morse.put("a" , ".-");
12: 	morse.put("b" , "-...");
13: 	morse.put("c" , "-.-.");
14: 	morse.put("d" , "-..");
15: 	morse.put("e" , ".");
16: 	morse.put("f" , "..-.");
17: 	morse.put("g" , "--.");
18: 	morse.put("h" , "....");
19: 	morse.put("i" , "..");
20: 	morse.put("j" , ".---");
21: 	morse.put("k" , "-.-");
22: 	morse.put("l" , ".-..");
23: 	morse.put("m" , "--");
24: 	morse.put("n" , "-.");
25: 	morse.put("o" , "---");
26: 	morse.put("p" , ".--.");
27: 	morse.put("q" , "--.-");
28: 	morse.put("r" , ".-.");
29: 	morse.put("s" , "...");
30: 	morse.put("t" , "-");
31: 	morse.put("u" , "..-");
32: 	morse.put("v" , "...-");
33: 	morse.put("w" , ".--");
34: 	morse.put("x" , "-..-");
35: 	morse.put("y" , "-.--");
36: 	morse.put("z" , "--..");
37: 	morse.put(" " , "/");
38: 
39: 	System.out.println(morseHash("I never saw a purple cow"));
40:     }
41: 
42:     String morseHash(String s)
43:     {
44: 	 s = s.toLowerCase();
45: 	 String cipherText = "";
46: 
47: 	 for (int i = 0; i<s.length(); i++)
48: 	 {
49: 	     cipherText = cipherText + morse.get(s.substring(i,i+1)) + " ";
50: 
51: 	 }
52: 
53: 	 return cipherText;
54:     }
55: 
56:     public static void main(String[] args) {
57: 	// TODO code application logic here
58: 	new NNStringArray();
59:     }
60: }

6.8 Demorse Code Hashmap

Rewrite the Demorse Code program using Hashmap

6.8.1 Solution

 1: import java.util.HashMap;
 2: import java.util.Map;
 3: import java.util.Map.Entry;
 4: 
 5: public class NNStringArray {
 6: 
 7:     Map <String, String> morse = new HashMap<String, String>();
 8: 
 9:     NNStringArray()
10:     {
11: 	morse.put("a" , ".-");
12: 	morse.put("b" , "-...");
13: 	morse.put("c" , "-.-.");
14: 	morse.put("d" , "-..");
15: 	morse.put("e" , ".");
16: 	morse.put("f" , "..-.");
17: 	morse.put("g" , "--.");
18: 	morse.put("h" , "....");
19: 	morse.put("i" , "..");
20: 	morse.put("j" , ".---");
21: 	morse.put("k" , "-.-");
22: 	morse.put("l" , ".-..");
23: 	morse.put("m" , "--");
24: 	morse.put("n" , "-.");
25: 	morse.put("o" , "---");
26: 	morse.put("p" , ".--.");
27: 	morse.put("q" , "--.-");
28: 	morse.put("r" , ".-.");
29: 	morse.put("s" , "...");
30: 	morse.put("t" , "-");
31: 	morse.put("u" , "..-");
32: 	morse.put("v" , "...-");
33: 	morse.put("w" , ".--");
34: 	morse.put("x" , "-..-");
35: 	morse.put("y" , "-.--");
36: 	morse.put("z" , "--..");
37: 	morse.put(" " , "/");
38: 
39: 	System.out.println(demorseHash(".. / -. . ...- . .-. / ... .- .-- / .- / .--. ..- .-. .--. .-.. . / -.-. --- .--"));
40: 
41:     }
42: 
43: 
44:     String demorseHash(String s)
45:     {
46: 	String [] letters = s.split("\\s+");
47: 	String plaintext = "";
48: 
49: 	for (int i = 0; i<letters.length; i++)
50: 	{
51: 	    for (Entry<String, String> entry : morse.entrySet()) {
52: 		if (entry.getValue().equals(letters[i])) {
53: 		    plaintext = plaintext + entry.getKey();
54: 		}
55: 	    }
56: 	}
57: 	return plaintext;
58:     }
59: 
60: 	public static void main(String[] args) {
61: 	// TODO code application logic here
62: 	new NNStringArray();
63:     }
64: }

6: Strings, Arrays and Collections

6 Strings, Arrays and Collections

6.1 Print 2D Array

The following code creates a 3 x 3 tic-tac-toe grid filled with Xs.

 1: void tictactoe()
 2:    {
 3:       String [][] grid = new String[3][3];
 4: 
 5:       for(int i = 0; i<grid.length; i++)
 6:       {
 7: 	  for (int j = 0; j<grid.length; j++)
 8: 	  {
 9: 	      grid[i][j] = "X";
10: 	  }
11:       }
12:       printArray(grid);
13: 
14:    }

Write a method that will print a 2D array of any size. Test it using the 3 x 3 tic-tac-toe grid given above

6.1.1 Example

1: tictactoe()
2:  *** Output ***
3:  | X | X | X |
4:  | X | X | X |
5:  | X | X | X |

6.2 Chess Board

Create an 8 x 8 Array to represent a chess board. Print out the array with alternate ‘X’ and ‘O’ entries as shown in the example:

6.2.1 Example

 1: chess();
 2:  *** Output ***
 3:  | X | O | X | O | X | O | X | O |
 4:  | O | X | O | X | O | X | O | X |
 5:  | X | O | X | O | X | O | X | O |
 6:  | O | X | O | X | O | X | O | X |
 7:  | X | O | X | O | X | O | X | O |
 8:  | O | X | O | X | O | X | O | X |
 9:  | X | O | X | O | X | O | X | O |
10:  | O | X | O | X | O | X | O | X |

6.3 Digits to Words

Write a method that will convert digits into words

6.3.1 Example

1: System.out.println(digitsToWords("35001922"));
2:  *** Output ***
3: Three Five Oh Oh One Nine Two Two

6.4 Time to Words

Write a method that will convert time to words. For example, 4:10 is “Ten past four” and 4:55 is “Five to Five”

6.4.1 Example

 1: System.out.println(timeToWords("2:05"));
 2: System.out.println(timeToWords("2:47"));
 3: System.out.println(timeToWords("12:00"));
 4: System.out.println(timeToWords("2:00"));
 5: System.out.println(timeToWords("12:30"));
 6: System.out.println(timeToWords("4:29"));
 7: System.out.println(timeToWords("7:25"));
 8: System.out.println(timeToWords("12:45"));
 9: System.out.println(timeToWords("12:55"));
10:  *** Output ***
11: five past two
12: thirteen minutes to two
13: twelve o'clock
14: two o'clock
15: half past past twelve
16: twenty nine minutes past four
17: twenty five past seven
18: Quarter to one
19: five to one

6.5 Morse Code Arrays

Write a program using arrays that translates plain text into morse code.

A B C D E F G
.- -… -.-. -.. . ..-. –.
H I J K L M
…. .. .— -.- .-..
N O P Q R S T
-. .–. –.- .-.
U V W X Y Z
..- …- .– -..- -.– __..

6.5.1 Example

1: String s = "I never saw a purple cow"
2: 
3: morse(s)
4:  *** Output ***
5: .. / -. . ...- . .-. / ... .- .-- / .- / .--. ..- .-. .--. .-.. . / -.-. --- .--

6.6 Demorse Code Arrays

Now write a program using arrays that translates morse back to plain text.

6.6.1 Example

1: String s = ".. -././...-/./.-. .../.-/.-- .- .--./..-/.-./.--./.-../. -.-./---/.--"
2: 
3: deMorse(s)
4:  *** Output ***
5: "I never saw a purple cow"

6.7 Morse Code Hashmap

Rewrite the Morse Code program using Hashmap

6.7.1 Example

1: String s = "I never saw a purple cow"
2: morseHash(s)
3:  *** Output ***
4: .. / -. . ...- . .-. / ... .- .-- / .- / .--. ..- .-. .--. .-.. . / -.-. --- .--

6.8 Demorse Code Hashmap

Rewrite the Demorse Code program using Hashmap

6.8.1 Example

1: String s = ".. -././...-/./.-. .../.-/.-- .- .--./..-/.-./.--./.-../. -.-./---/.--"
2: deMorseHash(s)
3:  *** Output ***
4: "I never saw a purple cow"

– Arithmetic Solutions

5.1 Primes

Determine whether a given integer number is prime.

5.1.1 Solution

 1:  public class NNArithmetic {
 2:
 3:     NNArithmetic()
 4:     {
 5:
 6:         System.out.println(isPrime(7));
 7:     }
 8:
 9:     boolean isPrime(int a)
10:     {
11:         //Special cases
12:         if(a==1) return false;
13:         if(a==2) return true;
14:
15:          boolean prime = true;
16:          int count = 2;
17:
18:          do
19:          {
20:              if (a%count==0)
21:              {
22:                  prime = false;
23:              }
24:              count++;
25:          } while(prime == true && count*count <=a);
26:
27:          return prime;
28:     }
29:
30:      public static void main(String[] args)
31:      {
32:         new NNArithmetic();
33:      }
34:  }
35:

5.2 GCD

Use Euclid’s Algorithm to determine the Greatest Common Divisor of two positive integer numbers

5.2.1 Solution

 1:  public class NNArithmetic {
 2:
 3:     NNArithmetic()
 4:     {
 5:
 6:         System.out.println(gcd (1071, 462));
 7:         System.out.println(gcd (6, 35));
 8:         System.out.println(gcd (36, 63));
 9:     }
10:
11:
12:     int gcd(int a, int b)
13:     {
14:          if(b>a)  //Make sure the first number is largest
15:          {
16:              int temp = a;
17:              a = b;
18:              b = temp;
19:          }
20:
21:          while(b>0)
22:          {
23:              int remainder = a%b;
24:              a = b;
25:              b = remainder;
26:          }
27:
28:          return a;
29:      }
30:
31:      public static void main(String[] args)
32:      {
33:         new NNArithmetic();
34:      }
35:  }
36:

5.3 Coprimes

Determine whether two positive integer numbers are coprime. Two numbers are coprime if their greatest common divisor equals 1.

5.3.1 Solution

 1:  public class NNArithmetic {
 2:
 3:     NNArithmetic()
 4:     {
 5:          System.out.println(isCoprime(35,64));
 6:     }
 7:
 8:     int gcd(int a, int b)
 9:     {
10:          if(b>a)  //Make sure the first number is largest
11:          {
12:              int temp = a;
13:              a = b;
14:              b = temp;
15:          }
16:
17:          while(b>0)
18:          {
19:              int remainder = a%b;
20:              a = b;
21:              b = remainder;
22:          }
23:
24:          return a;
25:      }
26:
27:
28:     boolean isCoprime(int a, int b)
29:     {
30:           return (gcd(a,b) ==1) ? true : false;
31:     }
32:
33:      public static void main(String[] args)
34:      {
35:         new NNArithmetic();
36:      }
37:  }
38:

5.4 Totient Function

Calculate Euler’s totient function phi(m).
Euler’s so-called totient function phi(m) is defined as the number of positive integers r (1 <= r < m) that are coprime to m.
For example: m = 10: r = 1,3,7,9; thus phi(m) = 4. Note the special case: phi(1) = 1.

5.4.1 Solution

 1:  public class NNArithmetic {
 2:
 3:     NNArithmetic()
 4:     {
 5:         System.out.println(phi(10));
 6:     }
 7:
 8:     int gcd(int a, int b)
 9:     {
10:          if(b>a)  //Make sure the first number is largest
11:          {
12:              int temp = a;
13:              a = b;
14:              b = temp;
15:          }
16:
17:          while(b>0)
18:          {
19:              int remainder = a%b;
20:              a = b;
21:              b = remainder;
22:          }
23:
24:          return a;
25:      }
26:
27:     boolean isCoprime(int a, int b)
28:     {
29:           return (gcd(a,b) ==1) ? true : false;
30:     }
31:
32:     int phi(int m)
33:     {
34:          if (m==1) return 1; //Special Case
35:
36:          int phi = 0;
37:          for(int i = 1; i<m; i++)
38:          {
39:              if (isCoprime(m,i)) phi++;
40:          }
41:          return phi;
42:     }
43:
44:      public static void main(String[] args)
45:      {
46:         new NNArithmetic();
47:      }
48:  }
49:

5.5 Prime Factors

Write a method that prints the prime factors of a given positive integer

5.5.1 Solution

 1:  public class NNArithmetic {
 2:
 3:     NNArithmetic()
 4:     {
 5:         printPrimeFactors(315);
 6:         printPrimeFactors(98);
 7:     }
 8:
 9:     void printPrimeFactors(int n)
10:     {
11:          for(int i = 2; i*i<=n; i++)
12:          {
13:              while(n%i == 0)
14:              {
15:                  System.out.print(i + " ");
16:                  n = n/i;
17:              }
18:          }
19:          if(n>1) System.out.print(n + "\n");
20:          else System.out.println("");
21:     }
22:
23:      public static void main(String[] args)
24:      {
25:         new NNArithmetic();
26:      }
27:  }
28:

5.6 List of Primes

Given a range of integers by its lower and upper limit, construct a list of all prime numbers in that range.

5.6.1 Solution

 1:  public class NNArithmetic {
 2:
 3:     NNArithmetic()
 4:     {
 5:         printPrimesInRange(10,20);
 6:     }
 7:
 8:     boolean isPrime(int a)
 9:     {
10:         //Special cases
11:         if(a==1) return false;
12:         if(a==2) return true;
13:
14:          boolean prime = true;
15:          int count = 2;
16:
17:          do
18:          {
19:              if (a%count==0)
20:              {
21:                  prime = false;
22:              }
23:              count++;
24:          } while(prime == true && count*count <=a);
25:
26:          return prime;
27:     }
28:     void printPrimesInRange(int a , int b)
29:     {
30:          for (int i = a; i<=b; i++)
31:          {
32:              if (isPrime(i)) System.out.print(i + " ");
33:          }
34:          System.out.println("");
35:     }
36:      public static void main(String[] args)
37:      {
38:         new NNArithmetic();
39:      }
40:  }
41:

5.7 Goldbach’s Conjecture

Goldbach’s conjecture says that every positive even number greater than 2 is the sum of two prime numbers. Example: 28 = 5 + 23. It is one of the most famous facts in number theory that has not been proved to be correct in the general case. It has been numerically confirmed up to very large numbers. Write a predicate to find the two prime numbers that sum up to a given even number.

5.7.1 Solution

 1:  public class NNArithmetic {
 2:
 3:     NNArithmetic()
 4:     {
 5:         printGoldbachPair(28);
 6:         printGoldbachPair(1856);
 7:     }
 8:
 9:     boolean isPrime(int a)
10:     {
11:         //Special cases
12:         if(a==1) return false;
13:         if(a==2) return true;
14:
15:          boolean prime = true;
16:          int count = 2;
17:
18:          do
19:          {
20:              if (a%count==0)
21:              {
22:                  prime = false;
23:              }
24:              count++;
25:          } while(prime == true && count*count <=a);
26:
27:          return prime;
28:     }
29:     int [] goldbachPair(int n)
30:     {
31:          int count = 2;
32:          int [] pair = new int[2];
33:          boolean foundPair = false;
34:          while(foundPair == false && count <= n/2)
35:          {
36:              if(isPrime(count) && isPrime(n-count))
37:              {
38:                  foundPair = true;
39:                  pair [0] = count;
40:                  pair [1] = (n-count);
41:              }
42:              count++;
43:          }
44:          return pair;
45:     }
46:
47:     void printGoldbachPair(int n)
48:     {
49:          int [] pair = goldbachPair(n);
50:          System.out.println(pair[0] + " + " + pair [1] + " = " + n);
51:     }
52:
53:
54:      public static void main(String[] args)
55:      {
56:         new NNArithmetic();
57:      }
58:  }
59:

5.8 More Goldbach

Given a range of integers by its lower and upper limit, print a list of all even numbers and their Goldbach composition.
In most cases, if an even number is written as the sum of two prime numbers, one of them is very small. Very rarely, the primes are both bigger than say 50. Try to find out how many such cases there are in the range 2..3000.

5.8.1 Solution

 1:  public class NNArithmetic {
 2:
 3:     NNArithmetic()
 4:     {
 5:         printGoldbachList(9, 20);
 6:         printGoldbachList(1,2000,50);
 7:     }
 8:
 9:     boolean isPrime(int a)
10:     {
11:         //Special cases
12:         if(a==1) return false;
13:         if(a==2) return true;
14:
15:          boolean prime = true;
16:          int count = 2;
17:
18:          do
19:          {
20:              if (a%count==0)
21:              {
22:                  prime = false;
23:              }
24:              count++;
25:          } while(prime == true && count*count <=a);
26:
27:          return prime;
28:     }
29:     int [] goldbachPair(int n)
30:     {
31:          int count = 2;
32:          int [] pair = new int[2];
33:          boolean foundPair = false;
34:          while(foundPair == false && count <= n/2)
35:          {
36:              if(isPrime(count) && isPrime(n-count))
37:              {
38:                  foundPair = true;
39:                  pair [0] = count;
40:                  pair [1] = (n-count);
41:              }
42:              count++;
43:          }
44:          return pair;
45:     }
46:
47:     void printGoldbachPair(int n)
48:     {
49:          int [] pair = goldbachPair(n);
50:          System.out.println(pair[0] + " + " + pair [1] + " = " + n);
51:     }
52:
53:     void printGoldbachList(int a, int b)
54:     {
55:          if(a%2==1) a++; // make sure start on even number
56:          for (int i = a ; i<=b ; i+=2)
57:          {
58:              printGoldbachPair(i);
59:          }
60:
61:     }
62:
63:     void printGoldbachList(int a, int b, int min)
64:     {
65:          if(a%2==1) a++; // make sure start on even number
66:          for (int i = a ; i<=b ; i+=2)
67:          {
68:              int [] pair = goldbachPair(i);
69:              if(pair[0] > min && pair[1] > min) printGoldbachPair(i);
70:          }
71:     }
72:
73:      public static void main(String[] args)
74:      {
75:         new NNArithmetic();
76:      }
77:  }

5: Arithmetic

5.1 Primes

Determine whether a given integer number is prime.

5.1.1 Example

1:  System.out.println(isPrime(7));
2:   *** Output ***
3:  true

5.2 GCD

Use Euclid’s Algorithm to determine the Greatest Common Divisor of two positive integer numbers

5.2.1 Example

1:   System.out.println(gcd (1071, 462));
2:   System.out.println(gcd (6, 35));
3:   System.out.println(gcd (36, 63));
4:   *** Output ***
5:  21
6:  1
7:  9

5.3 Coprimes

Determine whether two positive integer numbers are coprime. Two numbers are coprime if their greatest common divisor equals 1.

5.3.1 Example

1:  System.out.println(isCoprime(35,64));
2:   *** Output ***
3:  true

5.4 Totient Function

Calculate Euler’s totient function phi(m).
Euler’s so-called totient function phi(m) is defined as the number of positive integers r (1 <= r < m) that are coprime to m.
For example: m = 10: r = 1,3,7,9; thus phi(m) = 4. Note the special case: phi(1) = 1.

5.4.1 Example

1:  System.out.println(phi(10));
2:   *** Output ***
3:  4

5.5 Prime Factors

Write a method that prints the prime factors of a given positive integer

5.5.1 Example

1:  printPrimeFactors(315);
2:  printPrimeFactors(98);
3:   *** Output ***
4:  3 3 5 7
5:  2 7 7

5.6 List of Primes

Given a range of integers by its lower and upper limit, construct a list of all prime numbers in that range.

5.6.1 Example

1:  printPrimesInRange(10,20);
2:   *** Output ***
3:  11 13 17 19

5.7 Goldbach’s Conjecture

Goldbach’s conjecture says that every positive even number greater than 2 is the sum of two prime numbers. Example: 28 = 5 + 23. It is one of the most famous facts in number theory that has not been proved to be correct in the general case. It has been numerically confirmed up to very large numbers.
Write a predicate to find the two prime numbers that sum up to a given even number.

5.7.1 Example

1:  printGoldbachPair(28);
2:  printGoldbachPair(1856);
3:   *** Output ***
4:  5 + 23 = 28
5:  67 + 1789 = 1856

5.8 More Goldbach

Given a range of integers by its lower and upper limit, print a list of all even numbers and their Goldbach composition.  In most cases, if an even number is written as the sum of two prime numbers, one of them is very small. Very rarely, the primes are both bigger than say 50.
Try to find out how many such cases there are in the range 2..3000.

5.8.1 Example

 1:  printGoldbachList(9, 20);
 2:  printGoldbachList(1,2000,50);
 3:   *** Output ***
 4:  3 + 7 = 10
 5:  5 + 7 = 12
 6:  3 + 11 = 14
 7:  3 + 13 = 16
 8:  5 + 13 = 18
 9:  3 + 17 = 20
10:  73 + 919 = 992
11:  61 + 1321 = 1382
12:  67 + 1789 = 1856
13:  61 + 1867 = 1928