Java Reference
In-Depth Information
while ( true ) {
printMenu() ;
int choice = getIntValue( "Enter your choice: " );
switch (choice) {
case 1:
characters .add( new Superhero(getStringValue( "Name: " ),
getIntValue( "Good Power[1-10]: " ), getIntValue( "Respect
:[1-10]: " )));
break ;
case 2:
characters .add( new Villain(getStringValue( "Name: " ),
getIntValue( "Evil Power[1-10]: " ), getIntValue( "
Narcissism[1-10]: " )));
break ;
case 3: return ;
}
}
}
public static void printMenu() {
System. out . println ( "1. Enter Superhero" );
System. out . println ( "2. Enter Villain" );
System. out . println ( "3. Finish Entering" );
} public static int getIntValue ( String prompt) {
int choice ;
Scanner keyboard = new Scanner(System. in) ;
System. out . print (prompt) ;
choice = keyboard. nextInt() ;
return choice ;
} public static String getStringValue(String prompt) {
String choice ;
Scanner keyboard = new Scanner(System. in) ;
System. out . print (prompt) ;
choice = keyboard.next() ;
return choice ;
}
}
We have added two auxiliary methods: getIntValue and getStringValue .Theyread
an integer or a string from the keyboard. This is a good design because each of the methods
is used multiple times. A possible output of the program follows. As usual, user input is in
italic.
1. Enter Superhero
2. Enter Villain
3. Finish Entering
Enter your choice:
1
Name: Superman
Good Power[1-10]:
8
Respect:[1-10]: 8
1. Enter Superhero
2. Enter Villain
3. Finish Entering
 
Search WWH ::




Custom Search