|
Spring Semester 2003 |
Take a look at these problems. Problems on the exam will be just like these.
if statements.
if quarters > 0 then System.out.println(quarters + "quarters");
if (1 + x > Math.pow(x, Math.sqrt(2)) y = y + x;
if (x = 1) y++; else if (x = 2) y = y + 2;
if (x && y == 0) p = new Point2D.Double(x, y);
if (1 <= x <= 10)
{ System.out.println("Enter y:");
y = console.readDouble();
}
if (s != "nickels" || s != "pennies"
|| s != "dimes" || s != "quarters")
System.out.print("Input error!");
if (input.equalsIgnoreCase("N") || "NO")
return;
int x = console.readDouble();
if (x != null) y = y + x;
language = "English";
if (country.equals("USA"))
if (state.equals("PR")) language = "Spanish";
else if (country.equals("China"))
language = "Chinese";
"Tom", "Dick" "Tom", "Tomato" "church", "Churchill" "car manufacturer", "carburetor" "Harry" hairy" "C++", "Car" "Tom", "Tom" "Car", "Carl" "car", "bar"
p, q,
and r.
p |
q |
r |
(p && q) || !r |
!(p && (q || !r)) |
|---|---|---|---|---|
| false | false | false | ? | ? |
| false | false | true | ? | ? |
| false | true | false | ? | ? |
| ? | ? | ? | ? | ? |
| ? | ? | ? | ? | ? |
| ? | ? | ? | ? | ? |
| ? | ? | ? | ? | ? |
| ? | ? | ? | ? | ? |
A && B is the same as B && A for any Boolean
conditions A and B?
ands = 0; if (x > 0) s++; if (y > 0) s++;
s = 0; if (x > 0) s++; else if (y > 0) s++;
!(x > 0 && y > 0)
!(x != 0 || y != 0)
!(country.equals("USA") && !state.equals("HI") && !state.equals("AK"))
!(x % 4 != 0 || !(x % 100 == 0 && x % 400 == 0))
-else problem, using the following
statement.
A student with a GPA of at least 1.5, but less than 2, is on probation.With less than 1.5, the student is failing.
== operator and the
equals method when comparing strings.
andr == s
where bothr.equals(s)
r and s are of type Rectangle.
r is null?
What happens when this code runs?
Rectangle r; ... if (r.equals(null)) r = new Rectangle(5, 10, 20, 30);
n equals
10 and whether a floating-point number x equals 10.
x
and y such that
Math.abs(x - y) is larger than 1000,
x and y are still identical except
for a roundoff error.
Point2D.Double p = ...
boolean xInside = false;
if (x1 <= p.getX() && p.getY() <= x2)
xInside = true;
boolean yInside = false;
if (y1 <= p.getY() && p.getY() <= y2)
yInside = true;
if (xInside && yInside)
g2.drawString("p is inside the rectangle.", x1, y1);
Rewrite this code to eliminate the explicit true and false values,
by setting xInside and yInside to the values of Boolean expressions.
| 1. |
Write a program (called One) that prints all real solutions to the quadratic equation
a x2 + b x + c = 0Read in a, b, c and use the quadratic formula. If the discriminant b2 - 4acis negative, display a message stating that there are no real solutions. |
Here's how your program should behave:
frilled.cs.indiana.edu%java One Please enter the value of a then press Enter : 1.0 Please enter the value of b then press Enter : -2.0 Please enter the value of c then press Enter : 1.0 2.0 2.0 frilled.cs.indiana.edu%java One Please enter the value of a then press Enter : 1 Please enter the value of b then press Enter : 0 Please enter the value of c then press Enter : 1 There are no solutions. frilled.cs.indiana.edu%java One Please enter the value of a then press Enter : 1 Please enter the value of b then press Enter : 2 Please enter the value of c then press Enter : 3 There are no solutions. frilled.cs.indiana.edu%java One Please enter the value of a then press Enter : 1 Please enter the value of b then press Enter : -3 Please enter the value of c then press Enter : 1 1.881966011250105 4.118033988749895 frilled.cs.indiana.edu%java One Please enter the value of a then press Enter : 0 Please enter the value of b then press Enter : 0 Please enter the value of c then press Enter : 3 3.0 is not zero frilled.cs.indiana.edu%java One Please enter the value of a then press Enter : 1 Please enter the value of b then press Enter : 0 Please enter the value of c then press Enter : 0 -0.0 0.0 frilled.cs.indiana.edu%java One Please enter the value of a then press Enter : 0 Please enter the value of b then press Enter : 0 Please enter the value of c then press Enter : 0 Identity: zero == zero. frilled.cs.indiana.edu% | |
| 2. |
Write a program (called Two) that takes user input describing a playing card in the shorthand
notation described below, and then prints the full description of the card.
| ||||||||||||||||||||
Here's a sample run of such a program:
frilled.cs.indiana.edu%java Two Enter the card notation: AS Ace of spades. frilled.cs.indiana.edu%java Two Enter the card notation: 2H Two of hearts. frilled.cs.indiana.edu%java Two Enter the card notation: CJ Unknown denomination of unknown colour. frilled.cs.indiana.edu%java Two Enter the card notation: JC Jack of clubs. frilled.cs.indiana.edu%java Two Enter the card notation: QK Queen of unknown colour. frilled.cs.indiana.edu%java Two Enter the card notation: QH Queen of hearts. frilled.cs.indiana.edu%java Two Enter the card notation: A D Unknown denomination of unknown colour. frilled.cs.indiana.edu%java Two Enter the card notation: A D Ace of unknown colour. frilled.cs.indiana.edu%java Two Enter the card notation: AD Ace of diamonds. frilled.cs.indiana.edu% | |||||||||||||||||||||
| 3. |
Write a program (called Three) that
|
Here are (essentially) all possible runs of your program:
frilled.cs.indiana.edu%java Three Please enter the value of a then press Enter : 1 Please enter the value of b then press Enter : 2 Please enter the value of c then press Enter : 3 The largest number is: 3.0 frilled.cs.indiana.edu%java Three Please enter the value of a then press Enter : 1 Please enter the value of b then press Enter : 3 Please enter the value of c then press Enter : 2 The largest number is: 3.0 frilled.cs.indiana.edu%java Three Please enter the value of a then press Enter : 2 Please enter the value of b then press Enter : 1 Please enter the value of c then press Enter : 3 The largest number is: 3.0 frilled.cs.indiana.edu%java Three Please enter the value of a then press Enter : 2 Please enter the value of b then press Enter : 3 Please enter the value of c then press Enter : 1 The largest number is: 3.0 frilled.cs.indiana.edu%java Three Please enter the value of a then press Enter : 3.0 Please enter the value of b then press Enter : 1.0 Please enter the value of c then press Enter : 2.0 The largest number is: 3.0 frilled.cs.indiana.edu%java Three Please enter the value of a then press Enter : 3.0 Please enter the value of b then press Enter : 2.0 Please enter the value of c then press Enter : 1.0 The largest number is: 3.0 frilled.cs.indiana.edu% | |
| 4. |
Write a program (called Four)
that creates a circle with radius 100 and center (110, 120). Ask the
user to specify the x and y coordinates of a point. If the point lies
inside the circle, then show a message "Congratulations!" Otherwise, show a
message "You missed." Feel free to use, and enhance with a method
the Circle class that we developed in the second set of problems.
|
Here's a sample run of such a program:
frilled.cs.indiana.edu%java Four Welcome. Circle created. Center is at: (110.0, 120.0) Radius is: 100.0 You will be asked to specify a point. First enter x, then enter y. Please enter x now: 110 Please enter y now: 120 Congratulations. frilled.cs.indiana.edu%java Four Welcome. Circle created. Center is at: (110.0, 120.0) Radius is: 100.0 You will be asked to specify a point. First enter x, then enter y. Please enter x now: -30 Please enter y now: 120 You missed. frilled.cs.indiana.edu%java Four Welcome. Circle created. Center is at: (110.0, 120.0) Radius is: 100.0 You will be asked to specify a point. First enter x, then enter y. Please enter x now: 170.98 Please enter y now: 190.05 Congratulations. frilled.cs.indiana.edu% | |
| 5. |
Write a program (called Five)
that asks the user to specify the radii of two circles. The
first circle has center (100, 200) and the second circle has center (200, 100).
Check to see if the circles intersect. If they intersect, then display a message
"Circles intersect." Otherwise, display "Circles don't intersect."
Hint: Compute the distance between the centers and compare it to the radii.
|
Here's a sample run of such a program:
frilled.cs.indiana.edu%java Five Welcome. Please specify the radius of the first circle: 10 Great. Now please specify the radius of the second circle: 10 Circles don't intersect. frilled.cs.indiana.edu%java Five Welcome. Please specify the radius of the first circle: 100 Great. Now please specify the radius of the second circle: 100 Circles intersect. frilled.cs.indiana.edu%java Five Welcome. Please specify the radius of the first circle: 70 Great. Now please specify the radius of the second circle: 71.42 Circles don't intersect. frilled.cs.indiana.edu%java Five Welcome. Please specify the radius of the first circle: 70 Great. Now please specify the radius of the second circle: 71.43 Circles intersect. frilled.cs.indiana.edu%java Five Welcome. Please specify the radius of the first circle: 140 Great. Now please specify the radius of the second circle: 1.414299 Circles don't intersect. frilled.cs.indiana.edu%java Five Welcome. Please specify the radius of the first circle: 140 Great. Now please specify the radius of the second circle: 1.4299 Circles intersect. frilled.cs.indiana.edu% | |
| 6. |
Write a program (called Six)
that prints the question Do you want to continue?and reads the user input. If the user input is any of the following:
|
Here's a sample run of such a program:
frilled.cs.indiana.edu%java Six Do you want to continue? Y OK frilled.cs.indiana.edu%java Six Do you want to continue? Yes OK frilled.cs.indiana.edu%java Six Do you want to continue? OK OK frilled.cs.indiana.edu%java Six Do you want to continue? suRe OK frilled.cs.indiana.edu%java Six Do you want to continue? Sure OK frilled.cs.indiana.edu%java Six Do you want to continue? whY nOt? OK frilled.cs.indiana.edu%java Six Do you want to continue? why not ? Bad input frilled.cs.indiana.edu%java Six Do you want to continue? N Terminating frilled.cs.indiana.edu%java Six Do you want to continue? NO Terminating frilled.cs.indiana.edu%java Six Do you want to continue? nO Terminating frilled.cs.indiana.edu%java Six Do you want to continue? No! Bad input frilled.cs.indiana.edu% | |
| 7. |
Write a program (called Seven)
that translates a letter grade into a number grade. Letter grades are
A, B, C, D, F possibly
followed by + or -. Their numeric values are 4, 3, 2, 1, and 0.
There is no F+ or F-. A + increases the numeric
value by 0.3, a - decreases it by 0.3. However an A+ has a
value of 4.0.
|
Here's a sample run of such a program:
frilled.cs.indiana.edu%java Seven Enter a letter grade: A+ The numeric value is: 4.0 frilled.cs.indiana.edu%java Seven Enter a letter grade: A + Bad input. frilled.cs.indiana.edu%java Seven Enter a letter grade: U- Bad input. frilled.cs.indiana.edu%java Seven Enter a letter grade: B- The numeric value is: 2.7 frilled.cs.indiana.edu%java Seven Enter a letter grade: C The numeric value is: 2.0 frilled.cs.indiana.edu%java Seven Enter a letter grade: F The numeric value is: 0.0 frilled.cs.indiana.edu%java Seven Enter a letter grade: D- The numeric value is: 0.7 frilled.cs.indiana.edu%java Seven Enter a letter grade: -- Bad input. frilled.cs.indiana.edu% | |
| 8. |
Write a program (called Eight)
that translates a number between 0 and 4 into the closest letter grade.
For example, the number 2.8 (which might have been the average of several grades) would
be converted to B-. Break ties in favor of the better grade; for example
2.85 should be a B.
|
Here's a sample run of such a program:
frilled.cs.indiana.edu%java Eight Enter numeric score then press Enter : 3.85 A frilled.cs.indiana.edu%java Eight Enter numeric score then press Enter : 3.84 A- frilled.cs.indiana.edu%java Eight Enter numeric score then press Enter : 3.5 A- frilled.cs.indiana.edu%java Eight Enter numeric score then press Enter : 3.49 B+ frilled.cs.indiana.edu%java Eight Enter numeric score then press Enter : 3.1 B frilled.cs.indiana.edu%java Eight Enter numeric score then press Enter : 10 A+ frilled.cs.indiana.edu%java Eight Enter numeric score then press Enter : -2 frilled.cs.indiana.edu%java Eight Enter numeric score then press Enter : -0.5 frilled.cs.indiana.edu% | |
| 9. |
Write a program (called Nine)
that reads in three strings and sorts them lexicographically.
|
Here's a sample run of such a program:
frilled.cs.indiana.edu%java Nine Enter three strings: Alpha Beta Gamma Alpha Beta Gamma frilled.cs.indiana.edu%java Nine Enter three strings: Alpha Gamma Beta Alpha Beta Gamma frilled.cs.indiana.edu%java Nine Enter three strings: Username User Use Use User Username frilled.cs.indiana.edu%java Nine Enter three strings: Alpha Alpha Alpha Alpha Alpha Alpha frilled.cs.indiana.edu%java Nine Enter three strings: Gamma gamma gama Gamma gama gamma frilled.cs.indiana.edu%java Nine Enter three strings: 10 1 2 1 10 2 frilled.cs.indiana.edu% | |
| 10. |
A year with 366 days is called a leap year. A year is a leap year if it is divisible by 4 (for example, the year
1980), except it is not a leap year if it is divisible by 100 (for example, the year 1900); however, it is a leap
year if it is divisible by 400 (for example, the year 2000). There were no exceptions before the introduction of
the Gregorian calendar on October 15, 1582 (for example, the year 1500 was a leap year). Write a program
(called Ten)
that asks
the user for a year and computes whether that year is a leap year or not.
|
Here's a sample run of such a program:
frilled.cs.indiana.edu%java Ten Please enter the year then press Enter : 1500 Leap year: 1500 frilled.cs.indiana.edu%java Ten Please enter the year then press Enter : 1900 1900 not a leap year! frilled.cs.indiana.edu%java Ten Please enter the year then press Enter : 1996 Leap year: 1996 frilled.cs.indiana.edu%java Ten Please enter the year then press Enter : 1997 1997 not a leap year! frilled.cs.indiana.edu%java Ten Please enter the year then press Enter : 2000 Leap year: 2000 frilled.cs.indiana.edu% | |
| 11. |
Write a program (called Eleven) that asks the user to enter a month
For February, print
|
Here's a sample run of such a program:
frilled.cs.indiana.edu%java Eleven Enter a month : 1 31 days frilled.cs.indiana.edu%java Eleven Enter a month : 2 28 or 29 days frilled.cs.indiana.edu%java Eleven Enter a month : 3 31 days frilled.cs.indiana.edu%java Eleven Enter a month : 4 30 days frilled.cs.indiana.edu%java Eleven Enter a month : 5 31 days frilled.cs.indiana.edu%java Eleven Enter a month : 12 31 days frilled.cs.indiana.edu%java Eleven Enter a month : 13 Bad input frilled.cs.indiana.edu%java Eleven Enter a month : 0 Bad input frilled.cs.indiana.edu%java Eleven Enter a month : 1.2 Exception in thread "main" java.lang.NumberFormatException: 1.2 at java.lang.Integer.parseInt(Integer.java:418) at java.lang.Integer.parseInt(Integer.java:458) at ConsoleReader.readInt(Eleven.java:58) at Eleven.main(Eleven.java:7) frilled.cs.indiana.edu% | |
| 12. |
Write a program (called Twelve) that reads in two floating-point numbers and tests BOTH
|
Here's a sample run of such a program:
frilled.cs.indiana.edu%java Twelve Comparing floating-point numbers. Enter the first number : 1.3456 Enter the second number: 1.3402 1.3456 and 1.3402 are the same up to two decimal places. 1.3456 and 1.3402 are within 0.01 of one another. Thanks for asking. frilled.cs.indiana.edu%java Twelve Comparing floating-point numbers. Enter the first number : 2.003 Enter the second number: 1.998 2.003 and 1.998 are NOT the same up to two decimal places. 2.003 and 1.998 are within 0.01 of one another. Thanks for asking. frilled.cs.indiana.edu%java Twelve Comparing floating-point numbers. Enter the first number : 1.998 Enter the second number: 1.990 1.998 and 1.99 are the same up to two decimal places. 1.998 and 1.99 are within 0.01 of one another. Thanks for asking. frilled.cs.indiana.edu%java Twelve Comparing floating-point numbers. Enter the first number : 1.0000001 Enter the second number: 0.9999999 1.0000001 and 0.9999999 are NOT the same up to two decimal places. 1.0000001 and 0.9999999 are within 0.01 of one another. Thanks for asking. frilled.cs.indiana.edu% | |
| 13. |
Enhance the BankAccount class by
Write a program (called |
Here's a sample run of such a program:
Notice that you are free to allow negative initial balances (resembling a loan) but the two methods that implement deposit and withdraw should behave as stated in the text of the problem (rejecting negative arguments and rejecting operations that result in a negative balance other than the initial creation of the account). If you want you can disallow initial negative balances as well.frilled.cs.indiana.edu%java Thirteen Hello, and welcome to JavaOne Bank. An account will be created for you. What will the initial balance be? Type it now: 20 The current balance in your account is: 20.0 You now want to make a deposit. How much? Type the amount here: 30 The current balance in your account is: 50.0 You now want to make a withdrawal. How much? Type it now: 100 Sorry, you cannot do that. The current balance in your account is: 50.0 Thanks for using class BankAccount. Good-bye! frilled.cs.indiana.edu%java Thirteen Hello, and welcome to JavaOne Bank. An account will be created for you. What will the initial balance be? Type it now: -20 The current balance in your account is: -20.0 You now want to make a deposit. How much? Type the amount here: 10 The current balance in your account is: -10.0 You now want to make a withdrawal. How much? Type it now: 10 Sorry, you cannot do that. The current balance in your account is: -10.0 Thanks for using class BankAccount. Good-bye! frilled.cs.indiana.edu%java Thirteen Hello, and welcome to JavaOne Bank. An account will be created for you. What will the initial balance be? Type it now: -30 The current balance in your account is: -30.0 You now want to make a deposit. How much? Type the amount here: -20 Sorry, you cannot do that. The current balance in your account is: -30.0 You now want to make a withdrawal. How much? Type it now: -40 The current balance in your account is: 10.0 Thanks for using class BankAccount. Good-bye! frilled.cs.indiana.edu% | |
| 14. | Write a program that reads in the name and hourly wage of an employee. Then ask how many hours the employee worked in the past week. Be sure to accept fractional hours. Compute the pay. Any overtime work (over 40 hours per week) is paid at 150 percent of the regular wage. Print a paycheck for the employee. |
Here's a sample run of such a program:
Notice it's up to you what you do when the input is out of range. Also, you don't need to use the classfrilled.cs.indiana.edu%java Fourteen Please enter employee's name then press Enter : Larry Bird Please enter hourly wage then press Enter : 12.50 Please enter hours worked then press Enter: 10 Paycheck for employee Larry Bird Hours worked: 10.0 Hourly wage: 12.5 Total payment: 125.0 frilled.cs.indiana.edu%java Fourteen Please enter employee's name then press Enter : Michael Jordan Please enter hourly wage then press Enter : 10 Please enter hours worked then press Enter: 50 Paycheck for employee Michael Jordan Hours worked: 50.0 Hourly wage: 10.0 Overtime hours: 10.0 Overtime hourly wage: 15.0 Total payment: 550.0 frilled.cs.indiana.edu%java Fourteen Please enter employee's name then press Enter : Dennis Rodman Please enter hourly wage then press Enter : 2 Please enter hours worked then press Enter: -4 Paycheck for employee Dennis Rodman Hours worked: -4.0 Hourly wage: 2.0 Total payment: -8.0 frilled.cs.indiana.edu% Employee developed in the previous chapter, the emphasis is here on decisions.
| |
Here are some more questions, followed by some more problems:
BankAccount and
BankAccount.
andnew BankAccount(5000);
BankAccount b;
BankAccount object?
System.in
Write just objects, not object variables.
Rectangle r = (5, 10, 15, 20); double x = BankAccount(10000).getBalance(); BankAccount b; b.deposit(10000); b = new BankAccount(10000); b.addCoins(new Coin(0.25, "quarters")); Purse p = null; p.addCoins(new Coin(0.25, "quarters")); Purse p = new Purse(); p.addCoins(new Coin());
BankAccount class. List all methods that
can be used to change a BankAccount object. List all methods that don't change the
BankAccount object.
b after the following operations?
BankAccount b = new BankAccount(10); b.deposit(5000); b.withdraw(b.getBalance() / 2);
b1 and b2 store objects of class BankAccount,
consider the following instructions.
Are the balances ofb1.deposit(b2.getBalance()); b2.deposit(b1.getBalance());
b1 and b2 now identical? Explain.
this reference?
Here are more problems, write programs for them.
In the examples that follow,
blue,
| 1. |
Write a program that asks for an initial balance amount. Create a
BankAccount object with that amount. Then ask for a deposit
amount and a withdrawal amount. Carry out the deposit and withdrawal, then
print the remaining balance. Use ConsoleReader from Lab Notes
Two, and please place your main method in the class
BankAccount. |
Here's a sample run of such a program:
frilled.cs.indiana.edu%javac BankAccount.java frilled.cs.indiana.edu%java BankAccount Hello, and welcome to JavaOne Bank. An account will be created for you. What will the initial balance be? Type it now: -40.2 The current balance in your account is: -40.2 You now want to make a deposit. How much? Type the amount here: 120.3 The current balance in your account is: 80.1 You now want to make a withdrawal. How much? Type it now: 34 The current balance in your account is: 46.099999999999994 Thanks for using class BankAccount. Good-bye! frilled.cs.indiana.edu% | |
| 2. |
Implement a class Employee. An employee has a name (a String)
and a salary (a double). Write a default constructor, a constructor with two
parameters (name and salary), and methods to return the name and salary. Write a small
program to test your class. |
Here's a sample run of such a program:
frilled.cs.indiana.edu%java Employee Creating a new employee. Please type the name: Larry Bird Please specify the salary: 200000 New employee has been created. Name of employee: Larry Bird Salary: 200000.0 Thank you for testing class Employee. frilled.cs.indiana.edu% | |
| 3. |
Implement a class Employee. An employee has a name (a String) and
a salary (a double). Write a default constructor, a constructor with
two parameters (name and salary), and methods to return the name and salary. Test
your program, then enhance the class by adding a method
that raises the employee's salary by a certain percentage. |
Here's a sample run of such a program:
frilled.cs.indiana.edu%java Employee Creating a new employee. Please type the name: Michael Jordan Please specify the salary: 300000 New employee has been created. Name of employee: Michael Jordan Salary: 300000.0 Raising the salary of Michael Jordan By what percentage (e.g., 10, 20, etc.)? 10.5 Name of employee: Michael Jordan Current salary: 331500.0 Thank you for testing class Employee. frilled.cs.indiana.edu% | |
| 4. |
Implement a class Car with the following properties. A car has a certain fuel
efficiency (measured in miles per gallon or liters per km -- pick one) and a certain amount
of fuel in the gas tank. The efficiency is specified in the constructor,and the initial fuel
level is 0. Supply a method drive that simulates driving the car for a certain
distance, reducing the fuel level in the gas tank, and methods getFuelLevel,
returning the current fuel level, and tank, to tank up. |
Sample usage of the class:
Should produce:
frilled.cs.indiana.edu%java Car 0.0 20.0 16.551724137931036 | |
| 7. |
Implement a class Student. For the purpose of this
exercise, a student has
To compute the latter, you also need to store the number of quizzes that the student took. |
Here's a sample run of such a program:
Should produce:
frilled.cs.indiana.edu%java Student Grade report for: Larry Total score: 27.0 Average score: 9.0 frilled.cs.indiana.edu% | |
| 8. |
Implement a class Product. A product has
Supply methods
|
Here's a sample run of such a program:
Should produce:
frilled.cs.indiana.edu%java Product Product name: Toaster Product price: 29.95 ------------------------------ Product name: Toaster Product price: 24.95 ------------------------------ Product name: Phone Product price: 35.55 ------------------------------ Product name: Phone Product price: 30.549999999999997 ------------------------------ frilled.cs.indiana.edu% | |
| 9. |
Implement a class Circle that has methods
|
Here's a sample run of such a program:
Should produce:
frilled.cs.indiana.edu%java Circle Please specify the radius of your circle: 1.0 Circle created. Area: 3.141592653589793 Circumference: 6.283185307179586 Good-bye! frilled.cs.indiana.edu%java Circle Please specify the radius of your circle: 3.14 Circle created. Area: 30.974846927333928 Circumference: 19.729201864543903 Good-bye! frilled.cs.indiana.edu% | |
| 10. |
Implement a class BeerCan with methods
|
Here's a sample run of such a program:
Could produce:
frilled.cs.indiana.edu%java BeerCan Please specify the height of the BeerCan. 2.5 Please specify the radius of the BeerCan. 1.0 The BeerCan has been created. Its surface area is: 15.707963267948966 Its volume is: 7.853981633974483 frilled.cs.indiana.edu%java BeerCan Please specify the height of the BeerCan. 2 Please specify the radius of the BeerCan. 1 The BeerCan has been created. Its surface area is: 12.566370614359172 Its volume is: 6.283185307179586 frilled.cs.indiana.edu% | |
Good luck and don't forget: the harder they seem the more you can learn from them.
But these problems are not difficult. They're just that: good practice.
Here are some more questions to be reviewed:
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;
x1 = (-b - Math.sqrt(b * b - 4 * a * c)) / 2 * a; x2 = (-b + Math.sqrt(b * b - 4 * a * c)) / 2 * a;
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?
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)
}
}
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);
}
}
2, 2.0, "2", and "2.0".
andx = 2; y = x + x;
s = "2"; t = s + s;
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
n is 23456, how do you find out
2 and 6? Do not convert the number to a string.
Hint: %, Math.log
final variable? Can you define a final
variable without supplying its value?
What are the values of the following expressions?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()
Some advice, at the end of this document:
Try to solve these problems to practice some of the things you learned
this week. In the examples that follow, your program's answers are always
in blue, to distinguish them from
what you would type as a user. Remember: the resulting programs are
elementary, and the problems are interesting.
These problems are from your book.
| 1. | Write a program that displays the squares, cubes, and fourth powers of the numbers 1-5. |
Here's a sample run of such a program:
frilled.cs.indiana.edu%java One First five powers of 1: 1 1 1 1 1 First five powers of 2: 2 4 8 16 32 First five powers of 3: 3 9 27 81 243 First five powers of 4: 4 16 64 256 1024 First five powers of 5: 5 25 125 625 3125 frilled.cs.indiana.edu% |
| 2. |
Write a program that prompts the user for two integers and then
prints
|
|
Here's a sample run with your program:
frilled.cs.indiana.edu%java Two Please enter your first integer number, then press Enter. 3 Please enter your second integer number, then press Enter. 6 3 + 6 = 9 3 - 6 = -3 3 * 6 = 18 avg(3, 6) = 4.5 dist(3, 6) = 3 max(3, 6) = 6 min(3, 6) = 3 frilled.cs.indiana.edu% |
| 3. |
Write a program that
|
Here's a sample run with your program:
frilled.cs.indiana.edu%java Three Please enter the measurement in meters: 100 Your original measurement of 100.0 meters has been converted. 0 miles, 328 feet, and 1.0078719999998889 inches. frilled.cs.indiana.edu%java Three Please enter the measurement in meters: 16000 Your original measurement of 16000.0 meters has been converted. 9 miles, 4983 feet, and 7.1495919999956445 inches. frilled.cs.indiana.edu% |
| 4. |
Write a program that prompts the user for a radius
and then prints
|
Here's a sample run with your program:
whitetip.cs.indiana.edu%java Four Please enter value for radius then hit enter. 100 Thank you. The radius is 100.0 Here are the computed values. Area of the circle: 31415.926535897932 Circumference: 628.3185307179587 Area of a sphere: 125663.70614359173 Volume of sphere: 41887.90204786391 whitetip.cs.indiana.edu%java Four Please enter value for radius then hit enter. 1 Thank you. The radius is 1.0 Here are the computed values. Area of the circle: 3.141592653589793 Circumference: 6.283185307179586 Area of a sphere: 12.566370614359172 Volume of sphere: 4.1887902047863905 whitetip.cs.indiana.edu% |
| 5. |
Write a program that asks the user for the lengths
of the sides of a rectangle. Then print
|
Here's a sample run with your program:
whitetip.cs.indiana.edu%java Five Please enter the value for the first side. 3 Thanks. Side one is 3.0 Please enter the value for the second side. 4 Thanks. Side two is 4.0 Area is: 12.0 Perimeter is: 14.0 Diagonal is: 5.0 whitetip.cs.indiana.edu%java Five Please enter the value for the first side. 1 Thanks. Side one is 1.0 Please enter the value for the second side. 1 Thanks. Side two is 1.0 Area is: 1.0 Perimeter is: 4.0 Diagonal is: 1.4142135623730951 whitetip.cs.indiana.edu% |
| 6. |
(Giving change) Implement a program that directs
a cashier how to give change. The program has two inputs:
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. |
Here's a sample run with your program:
frilled.cs.indiana.edu%java Six Type the amount due then press enter. 3.72 Type the amount received then press enter. 5 Give 1.28 in change as follows: 5 quarters 0 dimes 0 nickels 3 cents frilled.cs.indiana.edu%java Six Type the amount due then press enter. 0.08 Type the amount received then press enter. 0.5 Give 0.42 in change as follows: 1 quarters 1 dimes 1 nickels 2 cents frilled.cs.indiana.edu% |
| 7. |
Write a program that asks the user to input
|
Here's a sample run with your program:
frilled.cs.indiana.edu%java Seven Please enter the number of gallons then press enter. 32 Please enter the fuel efficiency (miles/gallon) then press enter. 16 Please enter the price per gallon, then press enter. 1.54 With the gas in the tank you can go 512.0 miles, at a cost of 9.625 per 100 miles. frilled.cs.indiana.edu%java Seven Please enter the number of gallons then press enter. 2.8 Please enter the fuel efficiency (miles/gallon) then press enter. 18.5 Please enter the price per gallon, then press enter. 1.48 With the gas in the tank you can go 51.8 miles, at a cost of 8.0 per 100 miles. frilled.cs.indiana.edu% |
| 8. |
Write a program that
|
Here's a sample run with your program:
frilled.cs.indiana.edu%java Eight Please enter an integer >= 1000: 2000 2,000 frilled.cs.indiana.edu%java Eight Please enter an integer >= 1000: 2000000 2000,000 frilled.cs.indiana.edu%java Eight Please enter an integer >= 1000: 2000000000 2000000,000 frilled.cs.indiana.edu%java Eight Please enter an integer >= 1000: -3000 -3,000 frilled.cs.indiana.edu%java Eight Please enter an integer >= 1000: 20 Exception in thread "main" [...] |
| 9. | 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. (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.) |
Here's a sample run with your program:
frilled.cs.indiana.edu%java Nine Please enter an integer between 1,000 and 999,999: 123,456 123456 frilled.cs.indiana.edu%java Nine Please enter an integer between 1,000 and 999,999: 1,000 1000 frilled.cs.indiana.edu%java Nine Please enter an integer between 1,000 and 999,999: 1000000,000 1000000000 frilled.cs.indiana.edu% |
| 10. |
(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.
|
Here's a sample run with your program:
frilled.cs.indiana.edu%java Ten +--+--+--+ | | | | +--+--+--+ | | | | +--+--+--+ | | | | +--+--+--+ frilled.cs.indiana.edu% |
| 11. |
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 that1 6 3 8 4
|
Here's a sample run with your program:
|
| 12. |
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.
|
| 13. |
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 sample run with your program:
frilled.cs.indiana.edu%java Thirteen 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, if you'd like. I am sorry, Dave. I cannot do that. frilled.cs.indiana.edu%java Thirteen 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? Get lost. I am sorry, Dave. I cannot do that. frilled.cs.indiana.edu% |
| 14. | This is somewhat tricky so there are lots of hints in the text.
You don't know yet how to program decisions, but it turns out that
there is a way to fake
them using
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
Hint: Note thatString answer = " not "; // note the spaces before and after not System.out.println( "You will" + answer.substring(0, 5 - 4 * n) + // sometimes not! "make it"); x + |x| is
x, except that you need to worry
about the possibility that x is zero so use:
|
Here's a sample run with your program:
frilled.cs.indiana.edu%java Fourteen Please enter number of gallons then press enter. 10 Please enter fuel efficiency in miles per gallon. 20 Please enter distance in miles you want to cover. 199 You will make it. frilled.cs.indiana.edu%java Fourteen Please enter number of gallons then press enter. 5 Please enter fuel efficiency in miles per gallon. 20 Please enter distance in miles you want to cover. 101 You will not make it. frilled.cs.indiana.edu% |
| 15. |
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: 1730 8 hours 30 minutes Please enter the first time: 1730 Please enter the second time: 0900 15 hours 30 minutes |
Here's a sample run with your program:
frilled.cs.indiana.edu%java Fifteen Please enter the first time: 0920 Please enter the second time: 1025 1 hours 5 minutes frilled.cs.indiana.edu%java Fifteen Please enter the first time: 1025 Please enter the second time: 0920 22 hours 55 minutes frilled.cs.indiana.edu% |
| 16. |
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.
|
| 17. |
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 |
Here's a sample run with your program:
frilled.cs.indiana.edu%java Seventeen * * * * ***** * * * * ***** * ***** * ***** * * * * ***** * * * * ***** *** * * * * * * *** frilled.cs.indiana.edu% |
| 18. |
Write a program that transforms numbers
into the corresponding month names Hint: Make a very long string in which you add spaces such that each month name has the same length."January February March......."
Then use
|
Here's a sample run with your program:
frilled.cs.indiana.edu%java Eighteen Please enter a month number from 1 to 12. 2 February frilled.cs.indiana.edu%java Eighteen Please enter a month number from 1 to 12. 12 December frilled.cs.indiana.edu%java Eighteen Please enter a month number from 1 to 12. 1 January frilled.cs.indiana.edu%java Eighteen Please enter a month number from 1 to 12. 14 Exception in thread "main" [...] frilled.cs.indiana.edu% |