Knights (Array Initializer)
William would spend his entire reign putting down rebellions, and insurrections. In England his Norman knights and other military forces were vastly outnumbered by the English people. His solution to the problem was to station military forces in the castles that he was building throughout England. William was a fanatic about population and property statistics. He authorized the Doomsday book to track English land ownership and he undoubtedly kept accurate numbers regarding his castles, knights, and nobles.
Earlier you used this code to create an array.
- //Declares a string array
- String[] anArray;
- //Creates space in memory for 5 strings
- anArray = new String[5];
- //Initialize elements
- anArray[0] = "The first invaders were the Romans.";
- anArray[1] = "The second invaders were the Anglo-Saxons.";
- anArray[2] = "The third invaders were the Jutes.";
- anArray[3] = "The fourth invaders were the Vikings.";
- anArray[4] = "The fifth invaders were the Normans.";
The code shown below achieves the same goal but with less coding. The code on line 4 is called an Array Initializer.
- import static java.lang.System.out;
- public class CastleKnights {
- public static void main(String[] args) {
- int[] castle = {250, 412, 630, 145, 77, 533, 132, 788, 956, 362};
- out.println("Castle Knights");
- for (int castleNum = 0; castleNum < 10; castleNum++) {
- out.print(castleNum);
- out.print("\t");
- out.println(castle[castleNum]);
- }
- }
- }
The code on line 5 below adds a String Array Initializer. This code on line 8 ("\t") is called an escape sequence. The \t instructs Java to insert a tab. This line instructs the system to return the value that exists in the array at the determined index number: out.println(castle[castleNum] + "\t" + castlename[castleNum]);
- import static java.lang.System.out;
- public class CastleKnights2 {
- public static void main(String[] args) {
- int[] castle = {250, 412, 630, 145, 77, 533, 132, 788, 956, 362};
- String[] castlename = {"Windsor", "Durham", "Norwich", "Pickering", "Arundel", "Colchester", "Pevensey", "Tutbury", "Warwick", "Tower of London"};
- out.println("Castle Knights \t Name");
- for (int castleNum = 0; castleNum < 10; castleNum++) {
- out.print(castleNum);
- out.print("\t");
- out.println(castle[castleNum] + "\t" + castlename[castleNum]);
- }
- }
- }
Use Save As to save the code files to your folder. Then compile the code files in the Command prompt window. Run the CastleKnights.java file and the CastleKnights2.java file.
Your output should look like this:
C:\javamike>java CastleKnights.java
Castle Knights
0 250
1 412
2 630
3 145
4 77
5 533
6 132
7 788
8 956
9 362
C:\javamike>java CastleKnights2.java
Castle Knights Name
0 250 Windsor
1 412 Durham
2 630 Norwich
3 145 Pickering
4 77 Arundel
5 533 Colchester
6 132 Pevensey
7 788 Tutbury
8 956 Warwick
9 362 Tower of London
< Regions (Passing Objects) Knights Transfer (Input) >