Testing the User's Response

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

No — the user might want to see the value of the polynomial when x is 0.0. Any other value has the same problem.

Testing the User's Response

In this program, no special number is suitable as a sentinel because any number is potential data. Because of this, there must be a prompt that asks if the user wants to continue, and another prompt that asks for data.

Here is an outline of the program:

class EvalPoly
{
  public static void main (String[] args )
  {

    double x;                      // a value to use with the polynomial
    String response = "y";         // "y" or "n"

    while ( response.equals("y") )    
    {
       // Get a value for x.

       // Evaluate the polynomial.

       // Print out the result.

       // Ask the user if the program should continue.
       // The user's answer is "response".
      
    }

  }
}

It is often useful to work on one aspect of a program at a time. Let us first look at the "prompting and looping" aspect and temporarily ignore the polynomial evaluation aspect.

The condition part of the while statement, response.equals("y") evaluates to true or false. Here is how this happens:

  • response is a reference to a String object.
  • A String object has both data and methods (as do all objects).
  • The data part of response is the characters the user types.
  • response has an equals() method that tests if another string is equal to it.
  • response.equals("y") tests if the String response is equal to the String "y".
  • The result of the test is true or false.

In other words, the condition response.equals("y") asks: did the user type a "y"?

QUESTION 16:

If the user types "yes" will the program continue?