Monday, 15 December 2014

// The "SelectionStringExercises1" class.  Pages 99-100.
// (from the Carter book) Exercise 3.2 (1 and 2).

// (1) For each of the following pairs of
// strings, state, with a reason, which string preceeds
// the other of the pair.  You must use the String method
// "compareTo" when comparing 2 strings.  Study Examples
// 1 and 2 before doing this exercise.  How does the
// "compareTo" method calculate differences between characters?
// (2) State and display the value of each expression.  The String
// method "equals" is used here and returns true or false.
public class SelectionStringExercises1
{
    public static void main (String[] args)
    {
       // Exercise 3.2 (1):
       // Part (1a):
       System.out.println ("cat".compareTo("dog"));
       // does "cat" preceed "dog"?  Why is the result -1?
       // Part (1b):
       System.out.println ("cat".compareTo("Cathy"));
       // does "cat" preceed "Cathy"?  Why is the result 32?
       // Part (1c):  
       System.out.println ("X ".compareTo(" X"));
       // does "X " preceed " X"?  Why is the result 56?
       // Part (1d):
       System.out.println ("cab".compareTo("CAR"));
       // does "cab" preceed "CAR"? Why is the result 32?
       // Part (1e):
       System.out.println ("XX".compareTo("X X"));
       // does "XX" preceed "X X"?  Why is the result 56?
       // Part (1f):
       System.out.println ("XY".compareTo("XY "));
       // does "XY" preceed "XY "?  Why is the result -1?
       // Part (1g):
       System.out.println ("375".compareTo("84"));
       // does "375" preceed "84"?  Why is the result -5?
       // Part (1h):
       System.out.println ("".compareTo(" "));
       // does "" preceed " "?  Why is the result -1?
       //
       // Exercise 3.2 (2) uses the String method "equals"
       // and returns true or false.
       // Part (2a):  true / false?
       System.out.println ("one".equals("one "));
       // Part (2b):  true / false?
       System.out.println ("two".equals("2"));
       // Part (2c):  true / false?  
       System.out.println ("Three".equals("Three"));
       // Part (2d):  true / false?
       System.out.println ("four".equals("for"));
       
    } // main method
} // SelectionStringExercises1 class

No comments:

Post a Comment