The problem Write a program that prompts the user to enter a number within the range of 1 through 10. The program should display the Roman numeral version of that number. If the number is outside the range of 1-10, the program should display an error message.
Breaking it down public static void main ( String [] args ) {
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner ( System . in );
// Get a number from the user.
System . out . print ( "Enter a number in the range of 1 - 10: " );
int number = keyboard . nextInt (); // User inputed number
//close stream
keyboard . close ();
// Get Roman numeral.
String romanNumerals = convertNumberToRomanNumeral ( number );
// Output to user
System . out . println ( romanNumerals );
}
/**
* Method should return a Roman numeral that represents
* the number input.
*
* @param number
* @return String that represents a Roman numeral
*/
static String convertNumberToRomanNumeral ( Integer number ) {
switch ( number ) {
case 1 :
return "I" ;
case 2 :
return "II" ;
case 3 :
return "III" ;
case 4 :
return "IV" ;
case 5 :
return "V" ;
case 6 :
return "VI" ;
case 7 :
return "VII" ;
case 8 :
return "VIII" ;
case 9 :
return "IX" ;
case 10 :
return "X" ;
default :
return "Invalid number." ;
}
}
Output Enter a number in the range of 1 - 10: 4
IV
Unit tests @Test
public void test_convertNumberToRomanNumeral (){
String five = RomanNumerals . convertNumberToRomanNumeral ( 5 );
assertEquals ( "V" , five );
}
@Test
public void test_convertNumberToRomanNumeral_invalid (){
String five = RomanNumerals . convertNumberToRomanNumeral ( 100 );
assertEquals ( "Invalid number." , five );
}
Level Up Validate user input to be within range that the program can process. How would you write a program that would process all numbers? Roman Numerals Converter posted by Justin Musgrove on 08 April 2014
Tagged: java and java-exercises-beginner
Share on: Facebook Google+