Section Problems Number 1 - Java Basics

Be prepared to discuss these problems in discussion section.

1. What does the following method do?

// pre: s1 != null, n2 != null
public static boolean m1(String s1, String s2)
{   assert s1 != null && s2 != null : "Violation of precondition: m1. A parameter is null";
    boolean s = s1.length() == s2. length();
    int i = 0;
    while( s && i < s1.length() )
    {   s = s1.charAt(i) == s2.charAt(i);
    return s;

2. N! (N factorial) is defined for integers greater than or equal to 0. 0! is defined as 1. For values greater than 0, N! = N * (N-1)!

There are several errors in the following method for calculating factorial. What are the problems and how should they be fixed?

// pre: n >= 0
// post: return n!
public static int fact(int n)
{   assert n >= 0 : "Violation of precondition: fact. parameter n less than 0";
    int result = 0;
    for(int i = 1; i < n; i++)
    {   result *= i;
    return result;

3. After fixing method fact run it. For what values of n does fact correctly calculate n! ? What is the cause of the limitation?

4. Complete the Java method getRomanNumeral.

// pre: n > 0
// post: returns the Roman numeral equivalent of n as a String
public static String getRomanNumeral(int n)

For example given 1998 the returned value should be "MCMXCVIII". See for details on Roman numerals. Do not attempt to put horizontal numbers over digits as suggested at the bottom of the website. Also see the Wikipedia entry for roman Numerals.

Here are some tests for the method getRomanNumeral(). Your method should pass these tests and you should add more tests.

if( getRomanNumeral(1).equals("I") )
    System.out.println( "Passed test 1");
    System.out.println( "Failed test 1");

if( getRomanNumeral(2).equals("II") )
    System.out.println( "Passed test 2");
    System.out.println( "Failed test 2");

if( getRomanNumeral(1998).equals("MCMXCVIII") )
    System.out.println( "Passed test 3");
    System.out.println( "Failed test 3");

if( getRomanNumeral(999).equals("CMXCIX") )
    System.out.println( "Passed test 4");
    System.out.println( "Failed test 4");

if( getRomanNumeral(3555).equals("MMMDLV") )
    System.out.println( "Passed test 5");
    System.out.println( "Failed test 5");

if( getRomanNumeral(5000).equals("MMMMM") )
    System.out.println( "Passed test 6");
    System.out.println( "Failed test 6");