5.4 Solutions

  1. A few examples:
    println();   println("A string");    println("two", "strings");
    abs(10)  // returns an int
    abs(-1.5)  // returns a float
    fill(255);   fill(0, 0, 255);     fill(0, 255, 0, 255);
    1. B - a perfect match for the parameters
    2. invalid - first argument must fit in an int (both methods would require casting for a long first argument)
    3. B - the least amount of widening - only first argument needs to be widened to an int
    4. invalid - second argument must fit in an int or a long (both methods would require casting for a float second argument)
    5. A - a perfect match for the parmeters (also couldn't work for B)
    6. B - less widening required (2 char to 2 int - method A would require one of the casts to a long which requires more widening)
  2.  
    void rollDie (int rolls)
    {
      if (rolls < 1)
        println("Invalid argument - rolls must be at least 1");
      for (int i = 1; i <= rolls; i++)
         println((int)random(1, 7));
    }
    
    void rollDie (int rolls, int faces)
    {
      if (rolls < 1)
        println("Invalid argument - rolls must be at least 1");
      if (faces < 4)
        println("Invalid argument - faces must be at leat 4");
      else
        for (int i = 1; i <= rolls; i++)
          println((int)random(1, faces+1));
    } 
  3.  
    int average(long a, long b)
    {
      return (int)((a + b) / 2);
    }
    
    float average(float a, float b)
    {
      return (a + b) / 2;
    }
    
    void setup()
    {
      int m = average(8, 7L);
      float x = average(2.0, 3);
      println(m);
      println(x);
    }