Chapter 4

<< Chapter 3 | HomeworkTrailIndex | Chapter 5 >>

Demo Code

Implement a class QuadraticEquation (you can start with the code below if you wish to save time) whose constructor receives the coefficients a, b, c of the quadratic equation ax2 + bx + c = 0. Supply methods getSolution1 and getSolution2 that get the solutions, using the quadratic formula. Write a test class QuadraticEquationTester (or use the sample one below if you wish) that constructs a QuadraticEquation object, and prints the two solutions. For example, if you make QuadraticEquation myProblem = new QuadraticEquation(2,5,-3), the solutions should be .5 and -3

Recall that if ax^2+bx+c=0 then x= \frac{-b \pm \sqrt{b^2-4ac}}{2a}

QuadraticEquationTester.java

public class QuadraticEquationTester
{
    public static void main(String[] args)
    {
        QuadraticEquation myProblem = new QuadraticEquation(2.0,5.0,-3.0);
        double x1 = myProblem.getSolution1();
        double x2 = myProblem.getSolution2();
        System.out.println(myProblem);
        System.out.println("The solutions are "+x1+" and "+x2);
        System.out.println("Expected .5 and -3");
    }
}

QuadraticEquation.java

public class QuadraticEquation
{
    public  QuadraticEquation (double theA, double theB, double theC )
    {
        a=theA;
        b=theB;
        c=theC;
    }
    public double getSolution1()
    {
        return 0;// your work here
    }
     public double getSolution2()
    {
         return 0;//your work here
    }
    public String toString()
    {
          return a+"x^2 + "+b+"x + "+c+" =0";
    }

    private double a,b,c;
}

Write a method that gets the last n characters from a string. For example, last("Hello, World!", 5) should return the string "orld!".

public class Strings
{
   /**
      Gets the last n characters from a string.
      @param s a string
      @param n a nonnegative integer <= s.length()
      @return the string that contains the last n characters of s
   */
   public String last(String s, int n)
   {
      // your work here



   }
}

Complete the following function that computes the length of a line segment with end points (x1, y1) and (x2, y2). According to the Pythagorean theorem, the length is \sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2}.

public class Lines
{
   /**
      Computes the length of a line segment
      @param x1 the x-coordinate of the starting point
      @param y1 the y-coordinate of the starting point
      @param x2 the x-coordinate of the ending point
      @param y2 the y-coordinate of the ending point
      @return the length of the line segment joining (x1, y1) and (x2, y2)
   */
   public double segmentLength(double x1, double y1, double x2, double y2)
   {
      // your work here
      . . .
   }
}

Review Exercises

These are important activities to do, but not really something I can grade. This is like the "Training ground" in a video game where you learn the buttons before you go out on a quest. Skip these, and you may not last very long in the game. For each of these, make a guess, and then type the code, and see if the computer behaved the way you expected. True learning happens when you are surprised by a result, and you figure out what it did what it did!

  • R4.1 Write the following mathematical expressions in Java.
s=s_0+v_0t+\frac{1}{2}gt^2
G=4\pi^2\frac{a^3}{p^2(m_1+m_2)}
FV=PV\cdot\left(1+\frac{INT}{100}\right)^{YRS}
c=\sqrt{a^2+b^2-2ab\cos \theta}
  • R4.2 Write the following Java expressions in mathematical notation.
a. dm = m * (Math.sqrt(1 + v / c) / (Math.sqrt(1 - v / c) - 1));
b. volume = Math.PI * r * r * h;
c. volume = 4 * Math.PI * Math.pow(r, 3) / 3;
d. p = Math.atan2(z, Math.sqrt(x * x + y * y));
  • R4.5 What does Java report 4.35 * 100.0? Why?
  • R4.7 Let n be an integer and x a floating-point number. Explain the difference between

n = (int) x; and n = (int) Math.round(x);

  • R4.10
  • R4.11 If x is an int and s is a String, then which are true?
a. Integer.parseInt(“” + x) is the same as x
b. “” + Integer.parseInt(s) is the same as s
c. s.substring(0, s.length()) is the same as s
  • R4.13 How do you get the last digit of an integer? The first digit? That is, if n is 23456, how do you find out that the first digit is 2 and the last digit is 6?

Do not convert the number to a string. Hint: try % or Math.log. If you use the Math.log method, Java uses the natural log, and you want base 10.

 double logn = Math.log(n) / Math.log(10); // 10 to what power is 23456? about 4.37025395296 
  int ndigits = (int) logn; // round to 4.
  int pow10 = (int) Math.pow(10, ndigits); //four zeros: 10000
  int first = n / pow10; // 23456 over 1000 is 2.

Don't worry, we'll see this task later when we have loops and conditional statements, and that process will seem easier.

  • R4.16

Programming Exercises

For 8 points chose 2 of these four, for 9 points, chose 3 out of these four, and for 10 points, do all four

  • P4.11 Giving Change

Enhance the CashRegister class so that it directs a cashier how to give change. The cash register computes the amount to be returned to the customer, in pennies.

Add the following methods to the CashRegister class:

  • int giveDollars()
  • int giveQuarters()
  • int giveDimes()
  • int giveNickels()
  • int givePennies()

Each method computes the number of dollar bills or coins to return to the customer, and reduces the change due by the returned amount. You may assume that the methods are called in this order. Here is a test class:

public class CashRegisterTester
{
   public static void main(String[] args)
   {
      CashRegister register = new CashRegister();

      register.recordPurchase(8.37);
      register.enterPayment(10, 0, 0, 0, 0);
      System.out.println("Dollars: " + register.giveDollars());
      System.out.println("Expected: 1");
      System.out.println("Quarters: " + register.giveQuarters());
      System.out.println("Expected: 2");
      System.out.println("Dimes: " + register.giveDimes());
      System.out.println("Expected: 1");
      System.out.println("Nickels: " + register.giveNickels());
      System.out.println("Expected: 0");
      System.out.println("Pennies: " + register.givePennies());
      System.out.println("Expected: 3");
   }
}
  • P4.12 Split a number by digits

Write a program that reads in an integer and breaks it into a sequence of individual digits in reverse order. For example, the input 16384 is displayed as

4
8
3
6
1

You may assume that the input has no more than five digits and is not negative.

Define a class DigitExtractor:

public class DigitExtractor
{
   /**
      Constructs a digit extractor that gets the digits
      of an integer in reverse order.
      @param anInteger the integer to break up into digits
   */
   public DigitExtractor(int anInteger) { . . . }

   /**
      Returns the next digit to be extracted.
      @return the next digit
   */
   public int nextDigit() { . . . }
}

In your main class DigitPrinter, call System.out.println(myExtractor.nextDigit()) five times.

  • P4.15 Write large letters.

Writing large letters. A large letter H can be produced like this:

*   * 
*   *
*****
*   *
*   *

Use the class:

 public class LetterH
{
   public String toString()
   {
      return "*   *\n*   *\n*****\n*   *\n*   *\n";
   }
}

Define similar classes for the letters E, L, and O. Then write the message

H
E
L
L
0

in large letters.

Your main class should be called HelloPrinter.

  • P4.18 Gauss' Easter Algorithm

Write a class to compute the date of Easter Sunday. Easter Sunday is the first Sunday after the first full moon of spring. Use this algorithm, invented by the mathematician Carl Friedrich Gauss in 1800:

Let y be the year (such as 1800 or 2001).

Divide y by 19 and call the remainder a. Ignore the quotient.

Divide y by 100 to get a quotient b and a remainder c.

Divide b by 4 to get a quotient d and a remainder e.

Divide 8 * b + 13 by 25 to get a quotient g. Ignore the remainder.

Divide 19 * a + b - d - g + 15 by 30 to get a remainder h. Ignore the quotient.

Divide c by 4 to get a quotient j and a remainder k.

Divide a + 11 * h by 319 to get a quotient m. Ignore the remainder.

Divide 2 * e + 2 * j - k - h + m + 32 by 7 to get a remainder r. Ignore the quotient.

Divide h - m + r + 90 by 25 to get a quotient n. Ignore the remainder.

Divide h - m + r + n + 19 by 32 to get a remainder p. Ignore the quotient.

Then Easter falls on day p of month n. For example, if y is 2001:

a = 6                g = 6                r = 6
b = 20               h = 18               n = 4
c = 1                j = 0, k = 1         P = 15
d = 5, e = 0         m = 0

]@
Therefore, in 2001, Easter Sunday fell on April 15. Write a class @@Easter@@ with methods @@getEasterSundayMonth@@ and @@getEasterSundayDay@@.
Use the following class as your tester class:

[@
/**
   This program tests the Easter class.
*/
public class EasterTester
{
   public static void main(String[] args)
   {
      Easter myEaster = new Easter(2001);

      System.out.println("Month: " + myEaster.getEasterSundayMonth());
      System.out.println("Expected: 4");
      System.out.println("Day: " + myEaster.getEasterSundayDay());
      System.out.println("Expected: 15");
   }
}