CSCI A201/A597

Lab Notes Three

Second Summer 2000


Use this lab to make sure you get all your questions about chapter 2, take home quiz 2 and program assignment 2 answered.

Note that Takehome Quiz Two and Problem Problem Set Two have been posted last week and are due on Tuesday and Wednesday respectively.

You should get together with your group (find out who has your problem) and start working on the assignment.

To give you a bit of help here's a list of hints, one per problem.

Questions:

Hints are presented in blue.
  1. Write the following mathematical expressions in Java.




    This should not present any problem, but please be careful with default order of evaluation, and use methods from class Math for square root, cosine, also remember that class Math contains a few constants defined in it.

  2. Write the following Java expressions in mathematical notation.
    dm = m * ((Math.sqrt(1 + v / c) / Math.sqrt(1 - v / c)) - 1);
    volume = Math.PI * r * r * h;
    volume = 4 * Math.PI * Math.pow(r, 3) / 3; 
    This is the reverse of the previous problem. To just give you a pointer in the text I will mention here page 71, but of course much of chapter 2 is on this topic.

  3. What is wrong with this version of the quadratic formula?
    x1 = (-b - Math.sqrt(b * b - 4 * a * c)) / 2 * a; 
    x2 = (-b + Math.sqrt(b * b - 4 * a * c)) / 2 * a;
    This is the same as saying that there is a difference between
    2 / 3 * 1000
    and
    2 / (3 * 1000)
    In fact, is there a difference between the two?

  4. Give an example of integer overflow. Would the same example work correctly if you used floating-point?

    Give an example of a floating-point roundoff error. Would the same example work correctly if you used integers? When using integers, you would of course need to switch to a smaller unit, such as cents instead of dollars or milliliters instead of liters.

    Roundoff and overflow errors are mentioned in the book. Note that the questions asks more than to just find the sections in your text where these topics are mentioned (pp. 62, 53, etc.)

  5. Let n be an integer and x a floating-point number. Explain the difference between
    n = (int)x;
    and
    n = (int)Math.round(x);
    For what values of x do they give the same result? For what values of x do they give different results? What happens if x is negative?

    To start thinking about this problem read common error 2.2 in your text.

  6. Find at least five syntax errors in the following program.
    public class WarmUpSix
    { public static void main(String[] args) 
      { System.out.print("This program adds two numbers.),
        x = 5; 
        int y = 3.5;
        System.out.print("The sum of " + x + " and " + y " is: "); 
        System.out.println(x + y)
      }
    }

    Syntax errors are those that a compiler would detect. Come to think of it, if you're completely lost you could try to compile the program above. As soon as you notice an error write it down, fix it, and recompile. By the time your program compiles without error you will have the answer to this problem.

  7. Find at least three logic errors in the following program.
    public class WarmUpSeven 
    { public static void main(String[] args) 
      { ConsoleReader console = new ConsoleReader(System.in);
        int total = 1; 
        System.out.println("Please enter a number:"); 
        int x1 = Integer.parseInt(console.readLine()); 
        total = total + x1; 
        System.out.println("Please enter another number:"); 
        int x2 = Integer.parseInt(console.readLine()); 
        total = total + x1; 
        double average = total / 2;
        System.out.println("The average of two numbers is " 
          + average); 
      }
    }

    For this you need to assume that the program should compute the average of two numbers obtained from the user of the program.

  8. Explain the difference between 2, 2.0, "2", and "2.0".

    This is easy: the four constants are of exactly three different types. How many of these types are primitive types?

  9. Explain what each of the following two program segments computes:
    x = 2; 
    y = x + x;
    and
    s = "2";
    t = s + s; 

    You need to describe what y and t contain (or point to) at the end. Some of this is explained in the book on page 77 or thereabouts.

  10. Uninitialized variables can be a serious problem. Should you always initialize every variable with zero? Explain the advantages and disadvantages of such a strategy.

    I'll leave this one up to you. By the way, what is 3/0?

  11. True or false? (x is an int and s is a String)

    For this you need to think of what kind of argumenr parseInt expects, and how substring and length work on Strings. Then, try to come up with the answers. Finally, you can write a short program to test your answers on a few selected cases.

  12. Give two ways for converting a number to a string. What is the advantage of each of these ways?

    Section 2.6 in the book might contain useful information on that (perhaps not from the very beginning, but it's a long section).

  13. How do you get the first character of a string? The last character? How do you remove the first character? The last character?

    Section 2.6.2 will be useful here. Remember though that Strings are immutable objects, and be creative, using the tools (methods) that the section describes.

  14. How do you get the last digit of a number? The first digit? That is, if n is 23456, how do you find out 2 and 6? Do not convert the number to a string. Hint: %, Math.log

    To get the last digit should be easy. For the first digit you need to remember that taking the logarithm in base 10 of a number will give you the number of digits in that number minus 1 (this is an immediate consequence of the definition of the logarithm function).

  15. What is a final variable? Can you define a final variable without supplying its value?

    The book has the answer in section 2.4 somewhere.

  16. What are the values of the following expressions? In each line, assume that
    double x = 2.5;
    double y = -1.5;
    int m = 18;
    int n = 4;
    String s = "Hello";
    String t = "World"; 
    Remember that you can check each one of your answers by writing a program to print the values of each one of the expressions above. While this is somewhat reassuring it should also mean that you're encouraged to "think first, and experiment later".

And now some hints and clarifications on the problems.

1. Write a program that displays the squares, cubes, and fourth powers of the numbers 1-5.

Don't do any calculations yourself, make the computer do them. You have to compute the squares, cubes, and fourth powers of 5 numbers. You can use Math functions.


2. Write a program that prompts the user for two integers and then prints

  • The sum
  • The difference
  • The product
  • The average
  • The distance (absolute value of the difference)
  • The maximum (the larger of the two)
  • The minimum (the smaller of the two)

First get the integers from the user, then do the calculations.


3. Write a program that prompts the user for a measurement in meters and then converts it into miles, feet and inches.

You need to know the rate of conversion from meters to miles. It would be OK if you were to transform meters in yards, feet and inches. One meter is 1.093 yards, and is 39.37 inches.


4. Write a program that prompts the user for a radius and then prints

  • The area and circumference of the circle with that radius
  • The volume and surface area of the sphere with that radius

Once you get the radius you need to apply the formulas.


5. Write a program that asks the user for the lengths of the sides of a rectangle. Then print

  • The area and perimeter of the rectangle
  • The length of the diagonal (use the Pythagorean theorem)

You need to apply three formulas here. Writing the program is easy once you know the formulas.


6. Giving change. Implement a program that directs a cashier how to give change. The program has two inputs: the amount due and the amount received from the customer. Compute the difference, and compute the dollars, quarters, dimes, nickels, and pennies that the customer should receive in return. Hint: First transform the difference into an integer balance, denominated in pennies. Then compute the whole dollar amount. Subtract it from the balance. Compute the number of quarters needed. Repeat for dimes and nickels. Display the remaining pennies.

Integer division and using the modulus operator (%) operator to get the remainder should prove their usefulness in this problem.


7. Write a program that asks the user to input
  • The number of gallons
  • The fuel efficiency
  • The price
Then print how far the car can go with the gas in the tank and print the cost per 100 miles.

Here you need to come up with your own formulas for the distance that the car can travel with the gas it has and then for the car's mileage cost, given the price of the gasoline.


8. DOS file names and extensions. Write a program that prompts the user for the drive letter (C), the path (\Windows\System), the file name (ReadMe), and the extension (TXT). Then print the complete file name
C:\Windows\System\ReadMe.TXT
If you use Unix or a Macintosh, use / or : instead to separate directories).

Working with Strings and ConsoleReader so review 2.6 and 2.7 from the book if you don't know how to work with any them.


9. Write a program that reads a number greater than or equal to 1000 from the user and prints it out with a comma separating the thousands. Here is a sample dialog; the user input is in color:
Please enter an integer >= 1000: 23456
23,456

Read the problem carefully. You need to add only one comma (just one) in the representation of the number, to separate the thousands. The problem that follows is somewhat related too.


10. Write a program that reads a number greater than or equal to 1000 from the user, where the user enters a comma in the input. Then print the number without a comma. Here is a sample dialog; the user input is in color:
Please enter an integer between 1,000 and 999,999: 23,456
23456
Hint: Read the input as a string. Measure the length of the string. Suppose it contains n characters. Then extract substrings consisting of the first n - 4 characters and the last three characters.

This is the reverse of the preceding problem. Assume that the user is program-friendly and types the comma in the right place. Just as in the hint to the previous problem you need to remove just one comma, that the user typed to separate the thousands.


11. Printing a grid. Write a program that prints the following grid to play tic-tac-toe.
+--+--+--+
|  |  |  |
+--+--+--+
|  |  |  |
+--+--+--+
|  |  |  |
+--+--+--+
Of course, you could simply write seven statements of the form
System.out.println("+--+--+--+")
You should do it a smarter way, though. Define string variables to hold two kinds of patterns: a comb-shaped pattern and the bottom line. Print the comb three times and the bottom line once.

One or another this is a simple problem.


12. Write a program that reads an integer and breaks it into a sequence of individual digits. For example the input 16384 is displayed as
1 6 3 8 4
You may assume that the input has no more than five digits and is not negative. Hint: There are two ways of solving this problem. You can use integer arithmetic and repeatedly divide by 10, or you can convert the number into a string and extract the digits from the string.

The problem's hint is already more than needed, as far as how you go about solving this problem, so I will only make a comment on the interpretation of it, what the problem asks: essentially in your problem assume that you know the number already, and that it does not come from some user at run-time. So initialize a variable with the number of your choice and then compute the individual digits and print them.


13. The following program prints the values of sine and cosine for 0 degrees, 30 degrees, 45 degrees, 60 degrees, and 90 degrees. Rewrite the program for greater clarity by factoring out common code.
public class Thirteen 
{ public static void main(String[] args) 
  { System.out.println("0 degrees: " 
      + Math.sin(0) + " " + Math.cos(0)); 
    System.out.println("30 degrees: " 
      + Math.sin(30 * Math.PI / 180) + " " 
      + Math.cos(30 * Math.PI / 180)); 
    System.out.println("45 degrees: " 
      + Math.sin(45 * Math.PI / 180) + " " 
      + Math.cos(45 * Math.PI / 180)); 
    System.out.println("60 degrees: " 
      + Math.sin(60 * Math.PI / 180) + " " 
      + Math.cos(60 * Math.PI / 180)); 
    System.out.println("90 degrees: " 
      + Math.sin(90 * Math.PI / 180) + " " 
      + Math.cos(90 * Math.PI / 180)); 
  } 
} 

There's a "quality tip" somewhere in the book about this.


14. Write a program that prints out a message "Hello, my name is Hal!" Then, on a new line, the program should print the message "What is your name?" Next the program should read the user's name and print "Hello, user name. I am glad to meet you." Then, on a new line, the program should print a message "What would you like me to do?" Then it is the user's turn to type in an input. Finally the program should ignore the user input and and print the message "I am sorry, user name. I cannot do that."

Here's a typical program run. The user input is printed in color.

Hello, my name is Hal!
What is your name?
Dave
Hello, Dave. I am glad to meet you.
What would you like me to do? 
Clean up my room.
I am sorry, Dave. I cannot do that. 

Lab notes two (of last time, thursday) and section 2.7 in the book contain material related to what you need to accomplish here.


15. You don't know yet how to program decisions, but it turns out that there is a way to fake them using substring. Write a program that asks a user to input
  • The number of gallons of gas in the tank
  • The fuel efficiency in miles per gallon
  • The distance the user wants to travel
Then print out
You will make it
or
You will not make it
The trick here is to subtract the desired distance from the number of miles the user can drive. Suppose that the number is x. Suppose further that you find a way of setting a value n to 1 if x >= 0 and to 0 if x < 0. Then you can solve your problem:
String answer = " not "; // note the spaces before and after not
System.out.println("You will" + answer.substring(0, 5 - 4 * n)
  + "make it"); 
Hint: Note that x + |x| is 2x if x >= 0, and 0 if x < 0. Then divide by x, except that you need to worry about the possibility that x is zero.

All you have to do is to set n to 1 or 0 depending on the sign of x (see the hint above).


16. Write a program that reads two times in military format (0900, 1730) and prints the number of hours and minutes between the two times. Here is a sample run. User input is in color.
Please enter the first time: 0900
Please enter the second time: 1700
8 hours 30 minutes
Extra credit if you can deal with the case that the first time is later than the second time:
Please enter the first time: 1730
Please enter the second time: 0900
15 hours 30 minutes

I think Francisco's section (the lab that starts at 5pm) worked this problem out last Thursday in class -- so you will find it, or most of it, in the posted notes somewhere.


17. Run the following program, and explain the output you get.
public class Seventeen
{ public static void main(String[] args) 
  { ConsoleReader console = new ConsoleReader(System.in); 
    int total = 0; 
    System.out.println("Please enter a positive number:"); 
    int x1 = Integer.parseInt(console.readLine());
    System.out.println("total = " + total); 
    total = total + 1 / x1; 
    System.out.println("total = " + total); 
    System.out.println("Please enter a positive number:"); 
    int x2 = Integer.parseInt(console.readLine());
    total = total + 1 / x2; 
    System.out.println("total = " + total); 
    total = total * x1 * x2 / 2; 
    System.out.println("total = " + total); 
    System.out.println("The average is " + total); 
  }
}
Note the trace messages, which are inserted to show the current contents of the total variable. Then fix up the program, run it with the trace messages in place to verify that it works correctly, and remove the trace messages.

This is a debugging question.


18. Writing large letters. A large letter H can be produced like this:
*   *
*   *
*****
*   *
*   *
It can be declared as a string constant like this:
public static final String LETTER_H = 
  "*   *\n*   *\n*****\n*   *\n*   *\n";
Do the same for the letters E, L, and O. Then write the message
H
E
L
L
O

This problem is easy, and we solved a similar one in class, when we wrote a large ">".


19. Write a program that transforms numbers 1, 2, 3, ..., 12 into the corresponding month names January, February, March, ..., December. Hint: Make a very long string
"January February March. . ."
in which you add spaces such that each month name has the same length. Then use substring to extract the month you want.

If all month names are of the same length some will have to be padded with spaces, for all to match the longest name. What will the common length be after the extra padding with spaces? What will the total length of the resulting string be? How did you compute that? Use the same strategy to find the place where all the previous 11 substrings end.


20. Change the password program to make it generate more secure passwords. Use the random numner generator Random in the java.util package to generate a random number as follows:
int r = new Random().nextInt(1000);
Multiply the age by the random number. Then concentrate the initials with the last four digits of the product.

The password program is explained in section 2.6.4 in the textbook.


Last updated: June 26, 2000 by Adrian German for A201