| CSCI A201/A597Lab Notes Three Second Summer 2000 |
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.
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.
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.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 same as saying that there is a difference betweenx1 = (-b - Math.sqrt(b * b - 4 * a * c)) / 2 * a; x2 = (-b + Math.sqrt(b * b - 4 * a * c)) / 2 * a;
and2 / 3 * 1000
In fact, is there a difference between the two?2 / (3 * 1000)
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.)
n be an integer and x
a floating-point number. Explain the difference between
andn = (int)x;
For what values ofn = (int)Math.round(x);
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.
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.
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.
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?
andx = 2; y = x + x;
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.
I'll leave this one up to you.
By the way, what is 3/0?
x is an int and
s is a String)
Integer.parseInt("" + x) is the same as x
"" + Integer.parseInt(s) is the same as s
s.substring(0, s.length()) is the same as s
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.
Section 2.6 in the book might contain useful information on that (perhaps not from the very beginning, but it's a long section).
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.
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).
final variable? Can you define a final
variable without supplying its value?
The book has the answer in section 2.4 somewhere.
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".double x = 2.5; double y = -1.5; int m = 18; int n = 4; String s = "Hello"; String t = "World";
x + n * y - (x + n) * y
m / n + m % n
5 * x - n / 5
Math.sqrt(Math.sqrt(n))
(int)Math.round(x)
(int)Math.round(x) + (int)Math.round(y)
s + t
s + n
1 - (1 - (1 - (1 - (1 - n))))
s.substring(1, 3)
s.length() + t.length()
| 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
|
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
|
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
|
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
|
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
If you use Unix or a Macintosh, useC:\Windows\System\ReadMe.TXT / 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:
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.Please enter an integer between 1,000 and 999,999: 23,456 23456 |
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+--+--+--+ | | | | +--+--+--+ | | | | +--+--+--+ | | | | +--+--+--+
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
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.1 6 3 8 4 |
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.
|
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
orYou will make it The trick here is to subtract the desired distance from the number of miles the user can drive. Suppose that the number isYou will not make it 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:
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.
Extra credit if you can deal with the case that the first time is later than the second time:Please enter the first time: 0900 Please enter the second time: 1700 8 hours 30 minutes 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.
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:* * * * ***** * * * * Do the same for the letterspublic static final String LETTER_H = "* *\n* *\n*****\n* *\n* *\n"; 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
in which you add spaces such that each month name has the same length. Then use"January February March. . ." 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:
Multiply the age by the random number. Then concentrate the initials with the last four digits of the product.int r = new Random().nextInt(1000); |
The password program is explained in section 2.6.4 in the textbook.