Knights Transfer (Input)

Castle image

So, William the Conqueror had perhaps 10,000 Norman knights to rule over millions of English people. He needed a strategy that would allow the Normans to put down insurrections, rebellions, and attacks from Vikings. The solution was mobility. If an insurrection occurred in one region, his knights could shelter in their castle fortress until help could arrive from a nearby castle.

This code will allow you to ask for and receive input from a user of your program. Notice that you again import an object from the Java API (import java.util.Scanner;). See if you can follow the logic of the program. Notice the use of an if else conditional statement to check for an invalid number. When using the keyboard for input you should always close with the keyboard.close(); code.

  1. import static java.lang.System.out;
  2. import java.util.Scanner;
  3. public class KnightsTransfer {
  4. public static void main(String[] args) {
  5. int[] castle = {250, 412, 630, 145, 77, 533, 132, 788, 956, 362};
  6. String[] castlename = {"Windsor", "Durham", "Norwich", "Pickering", "Arundel", "Colchester", "Pevensey", "Tutbury", "Warwick", "Tower of London"};
  7. // The next line establishes "keyboard" as an instance of
  8. // the Scanner object with the "System.in" parameter.
  9. // The "System.in" parameter will hold the user's input.
  10. Scanner keyboard = new Scanner(System.in);
  11. out.print("Enter the number of the castle from which you want to transfer knights: ");
  12. int castleNum = keyboard.nextInt();
  13. if (castleNum > 9) {
  14. out.println("Number must be from 0 to 9");
  15. } else {
  16. out.print("How many knights would you like to transfer: ");
  17. int numberofknights = keyboard.nextInt();
  18. out.print("You have requested the transfer of " + numberofknights);
  19. out.print(" knights from " + castlename[castleNum]);
  20. out.println(" castle.");
  21. out.print("Enter the number of the castle to which you want to transfer knights: ");
  22. int castleNum2 = keyboard.nextInt();
  23. castleNum = castleNum2;
  24. out.print("William the Conquerer will send the knights to " + castlename[castleNum]);
  25. out.println(" castle.");
  26. }
  27. keyboard.close();
  28. }
  29. }

Java code

Use Save As to save the code file to your folder. Then compile the code file in the Command prompt window. Run the KnightsTransfer.java file.

Your output should look like this:

C:\javamike>java KnightsTransfer

Enter the number of the castle from which you want to transfer knights: 8

How many knights would you like to transfer: 30

You have requested the transfer of 300 knights from Warwick castle.

Enter the number of the castle to which you want to transfer knights: 9

William the Conqueror will send the knights to Tower of London castle.

 

< Knights (Array Initializer) Colonies (Nested If) >