– 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: }

Leave a Comment