/** * Matt Kretchmar * February 7, 2006 * NYC.java * This program allows the user to enter direction command (N,S,E,W) to * move a person around in New York City. The program keeps track of * how far the person has moved from their starting point and reports * the information back to the user at the end of input. A 'Q' signifies * the end of input. */ import java.util.Scanner; class NYC { public static void main ( String [] args ) { char code; // User's input code String s; // to help reading a character int blocksNorth; // number of blocks north from starting point int blocksEast; // number of blocks East from starting point Scanner keyboard = new Scanner(System.in); code = ' '; blocksNorth = 0; blocksEast = 0; while ( code != 'Q' ) { System.out.println("Enter direction code (N,E,S,W, or Quit): "); s = keyboard.next(); code = s.charAt(0); switch (code) { case 'N' : blocksNorth++; break; case 'S' : blocksNorth--; break; case 'E' : blocksEast++; break; case 'W' : blocksEast--; break; case 'Q' : break; default : System.out.println("ignoring invalid input"); } } if ( blocksNorth == 0 && blocksEast == 0 ) System.out.println("You are back at the starting point"); else { String sNorth; if ( blocksNorth == 0 ) sNorth = ""; else if (blocksNorth < 0 ) sNorth = (-1 *blocksNorth) + " blocks South"; else sNorth = blocksNorth + " blocks North"; String sEast; if ( blocksEast == 0 ) sEast = ""; else if (blocksEast < 0 ) sEast = (-1*blocksEast) + " blocks West"; else sEast = blocksEast + " blocks East"; String junction = ""; if ( blocksNorth != 0 && blocksEast != 0 ) junction = " and "; System.out.println("You are " + sNorth + junction + sEast + " of your starting point"); } } }