|
CSCI A201/A597 and I210
Homework One Solutions
Second semester 2000-2001
|
Here are example of solutions to the problems in this first set.
| 1. |
Write a program that displays the squares, cubes, and fourth
powers of the numbers 1-5.
|
| |
Here's a sample run of such 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%
|
/* This is the solution to the first problem of the first problem
set: it displays the first five powers of the first five numbers. This
is a bit of an overkill, but that's only because the problem is very
simple. Notice then that the third, fourth, and fifth powers are being
computed from previously calculated values. */
public class One {
public static void main(String[] args) {
int number = 1;
int square = number * number;
int fourthPower = square * square;
System.out.print("First five powers of " + number + ": ");
System.out.println( number + " " +
square + " " +
number * square + " " +
fourthPower + " " +
number * fourthPower );
// done with 1.
number += 1;
square = number * number;
fourthPower = square * square;
System.out.print("First five powers of " + number + ": ");
System.out.println( number + " " +
square + " " +
number * square + " " +
fourthPower + " " +
number * fourthPower );
// done with 2.
number += 1;
square = number * number;
fourthPower = square * square;
System.out.print("First five powers of " + number + ": ");
System.out.println( number + " " +
square + " " +
number * square + " " +
fourthPower + " " +
number * fourthPower );
// done with 3.
number += 1;
square = number * number;
fourthPower = square * square;
System.out.print("First five powers of " + number + ": ");
System.out.println( number + " " +
square + " " +
number * square + " " +
fourthPower + " " +
number * fourthPower );
// done with 4
number += 1;
square = number * number;
fourthPower = square * square;
System.out.print("First five powers of " + number + ": ");
System.out.println( number + " " +
square + " " +
number * square + " " +
fourthPower + " " +
number * fourthPower );
// done with 5
// -- finished
}
}
| 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)
|
| |
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%
|
/* This is the solution to the second problem in the first problem set.
Note that you need ConsoleReader, which is available from the second set
of lab notes (Lab Two) off the class notes page or from the book. Once you
get the Consolereader class off the web notes place it in a file of its
own, with the name ConsoleReader.java in the same directory with Two.java
whose source code is written below, then compile Two.java. For more details
see http://www.cs.indiana.edu/classes/a201/spr2001/labs/Two.html */
public class Two {
public static void main(String[] args) {
ConsoleReader console = new ConsoleReader(System.in);
System.out.print("Please enter your first integer number, ");
System.out.println("then press Enter.");
int n1 = console.readInt();
System.out.print("Please enter your second integer number, ");
System.out.println("then press Enter.");
int n2 = console.readInt();
int sum = n1 + n2;
System.out.println(n1 + " + " + n2 + " = " + sum);
int diff = n1 - n2;
System.out.println(n1 + " - " + n2 + " = " + diff);
int prod = n1 * n2;
System.out.println(n1 + " * " + n2 + " = " + prod);
double avg = sum / 2.0;
System.out.println("avg(" + n1 + ", " + n2 + ") = " + avg);
int dist = Math.abs(n1 - n2);
System.out.println("dist(" + n1 + ", " + n2 + ") = " + dist);
long max = Math.round(avg + dist / 2.0);
// neat trick; can you explain it?
System.out.println("max(" + n1 + ", " + n2 + ") = " + max);
long min = Math.round(avg - dist / 2.0);
// neat trick; can you explain it?
System.out.println("min(" + n1 + ", " + n2 + ") = " + min);
}
}
| 3. |
Write a program that
- prompts the user for a measurement in meters
- and then converts it into miles, feet and inches.
|
| |
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% |
/* This is the solution to the third problem on the first problem set. It
also needs the ConsoleReader class which can be taken from lab notes 2 (see
problem 2 above for more details). This is not a hard problem the difficulty
(if any) is *only* in the conversion formulas. I decided to use three named
constants to avoid magic numbers and I express miles and feet as integers,
while the number of inches is reported as a double. */
public class Three {
public static void main(String[] args) {
// create a console reader for user input, call it console
ConsoleReader console = new ConsoleReader(System.in);
// let the user know you're ready to receive input
System.out.println("Please enter the measurement in meters: ");
// get the measurement in meters from the user
double measurement = console.readDouble();
// define three constants needed in the conversion
final double METERS_PER_MILE = 1609;
final double METERS_PER_FOOT = 0.3048;
final double METERS_PER_INCH = 1/39.37;
// first compute the number of miles
int miles = (int) (measurement / METERS_PER_MILE);
// take those miles away from the measurement
// first make a copy of the original value of the measurement
double original = measurement;
// then take the miles away
measurement -= miles * METERS_PER_MILE;
// then compute the number of feet from the remaining distance
int feet = (int) (measurement / METERS_PER_FOOT);
// take the feet away from the measurement
measurement -= feet * METERS_PER_FOOT;
// then compute the number of inches in the remaining distance
double inches = (measurement / METERS_PER_INCH);
// print title of report
System.out.print("Your original measurement of ");
System.out.print(original);
System.out.print(" meters has been converted.\n");
// print conversion results
System.out.println(" " + miles + " miles,");
System.out.println(" " + feet + " feet, and");
System.out.println(" " + inches + " 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
|
| |
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% |
/* This is the solution to problem four in first problem set. Note
that just as in problem 2 you need to have the ConsoleReader class in
a file in the same directory before compiling this class */
public class Four {
public static void main(String[] args) {
// get a connection to the keyboard
ConsoleReader console = new ConsoleReader(System.in);
// let the user know you're ready to receive the value for the radius
System.out.println("Please enter value for radius then hit enter.");
// get the value
double radius = console.readDouble();
// echo value to user
System.out.println("Thank you. The radius is " + radius);
// apply formulas
double areaCircle = Math.PI * radius * radius;
double circumferenceCircle = 2 * Math.PI * radius;
double areaSphere = 4 * Math.PI * radius * radius;
double volumeSphere = 4 * Math.PI * radius * radius / 3;
// as you can see I have an error here in the volume formula!
// report the computed values
System.out.println("Here are the computed values.");
System.out.println("Area of the circle: " + areaCircle);
System.out.println("Circumference: " + circumferenceCircle);
System.out.println("Area of a sphere: " + areaSphere);
System.out.println("Volume of sphere: " + volumeSphere);
}
}
| 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)
|
| |
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 3.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%
|
/* This is the solution for the fifth problem in the first set. Like in
problem 2 you need to have ConsoleReader.java in the same directory before
compiling this class (Five.java). The problem gets the values from the user
and then applies formulas and reports the computed values. */
public class Five {
public static void main(String[] args) {
// get a connection to the keyboard
ConsoleReader console = new ConsoleReader(System.in);
// greet the user, ask for first value
System.out.println("Please enter the value for the first side.");
double side1 = console.readDouble();
// echo value to user
System.out.println("Thanks. Side one is " + side1);
// ask for second value
System.out.println("Please enter the value for the second side.");
double side2 = console.readDouble();
// echo second value
System.out.println("Thanks. Side two is " + side1); // side2!!
// apply formulas, compute required quantities
double area = side1 * side2;
double perimeter = (side1 + side2 ) * 2;
double diagonal = Math.sqrt(side1 * side1 + side2 * side2);
// report all computed value
System.out.println("Area is: " + area +
"\nPerimeter is: " + perimeter +
"\nDiagonal is: " + diagonal);
}
}
| 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.
|
| |
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%
|
/* This is the solution to problem six in first problem set. ConsoleReader is
needed, use it as described in problem 2. This is a typical problem in which you
carefully need to cover roundoff errors, so use Math.round after you transform
the problem in whole units (cents). */
public class Six {
public static void main(String[] args) {
// get a connection to the keyboard
ConsoleReader console = new ConsoleReader(System.in);
// ask the user for the amount due
System.out.println("Type the amount due then press enter.");
// read it
double due = console.readDouble();
// ask the user for the amount received
System.out.println("Type the amount received then press enter.");
// read it
double received = console.readDouble();
// assume received is bigger than due and compute difference
double difference = (received - due);
// you need to return this as change so make it a whole number
// of cents regardless of how many decimals the user has entered
int diff = (int)(Math.round(difference * 100));
// tell the user what change you are processing
System.out.println("Give " + diff / 100.00 + " in change as follows: ");
// number of quarters; integer division
int quarters = diff / 25;
// report it
System.out.println(" " + quarters + " quarters");
// adjust the remaining change (modulo)
diff = diff % 25;
// compute the number of dimes
int dimes = diff / 10;
// report it
System.out.println(" " + dimes + " dimes");
// adjust remaining cents (notice shortcut operator)
diff %= 10; // notice anything compared to the previous assignment?
// these are the cents
int cents = diff;
// report them too
System.out.println(" " + cents + " cents");
}
}
| 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'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%
|
/* This is the solution to problem seven in the first problem set.
Need ConsoleReader in the same directory before you can compile it,
just like in problem 2. Formulas used are straightforward, easy. */
public class Seven {
public static void main(String[] args) {
// get a connection to the keyboard
ConsoleReader console = new ConsoleReader(System.in);
// greet the user, ask for number of gallons
System.out.println("Please enter the number of gallons then press enter.");
// read number of gallons
double gallons = console.readDouble();
// ask for fuel efficiency
System.out.println("Please enter the fuel efficiency " +
"(miles/gallon) then press enter. ");
// read user input
double efficiency = console.readDouble();
// ask for price per gallon
System.out.println("Please enter the price per gallon, then press enter.");
// read price from user
double price = console.readDouble();
// computer how far the user can go with that much gas
double howFar = efficiency * gallons;
// compute how much that will cost
double totalCost = price * gallons;
// divide this by howFar and multiply by 100 to get price per 100 miles
double pricePer100Miles = totalCost / howFar * 100;
System.out.println("With the gas in the tank you can go " +
howFar + " miles, \nat a cost of " +
pricePer100Miles + " per 100 miles.");
}
}
| 8. |
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'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" [...]
|
/* This is the solution to problem eight in the first set of problems. You
need ConsoleReader in the same directory before compiling, as detailed at
problem 2. Essentially you read a number as string, and write it back as
required, with a comma separating the thousands (the last three digits). As
before, no error checking is done, user is assumed to be program-friendly. */
public class Eight {
public static void main(String[] args) {
// get a connection to the keyboard
ConsoleReader console = new ConsoleReader(System.in);
// ask the user to enter a number
System.out.print("Please enter an integer >= 1000: ");
// read the number, assume the user types the right thing
String number = console.readLine();
// report the number with the comma separating the thousands
System.out.println(// first write digits up to thousands
number.substring(0, number.length() - 3) +
"," + // then write the comma
// and the remaining part (the thousands)
number.substring(number.length()-3));
}
}
| 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%
|
/* This is the solution to the nineth problem in the first problem
set. You need ConsoleReader in the same directory, as explained in
problem 2, before you can compile this program. This program assumes
that the user types in a number that contains a comma separating the
thousands from the rest of the number. */
public class Nine {
public static void main(String[] args) {
// get a connection to the keyboard
ConsoleReader console = new ConsoleReader(System.in);
// ask the user for input
System.out.print("Please enter an integer between 1,000 and 999,999: ");
// read user's input
String number = console.readLine();
// get the first part (no comma or thousands)
String firstPart = number.substring(0, number.length() - 4);
// get last three digits
String lastThreeDigits = number.substring(number.length() - 3);
// print the two without the comma
System.out.println(firstPart + lastThreeDigits);
}
}
| 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
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.
|
| |
Here's a sample run with your program:
frilled.cs.indiana.edu%java Ten
+--+--+--+
| | | |
+--+--+--+
| | | |
+--+--+--+
| | | |
+--+--+--+
frilled.cs.indiana.edu%
|
/* This is the solution to the tenth problem in the first problem
set. Given the hint it's straightforward. We define two patterns and we
print them accordingly to obtain the desired output. */
public class Ten {
public static void main(String[] args) {
// first pattern, comb-shaped
String comb = "+--+--+--+\n" +
"| | | |\n";
// second pattern, bottom line
String bottom = "+--+--+--+\n";
// print the grid for the user
System.out.println(comb + comb + comb + bottom);
}
}
| 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
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.
|
| |
Here's a sample run with your program:
frilled.cs.indiana.edu%java Eleven
Please enter a number between 0 and 99999: 123
1 2 3
frilled.cs.indiana.edu%java Eleven
Please enter a number between 0 and 99999: 0
0
frilled.cs.indiana.edu%java Eleven
Please enter a number between 0 and 99999: 83021
8 3 0 2 1
frilled.cs.indiana.edu%java Eleven
Please enter a number between 0 and 99999: 123456
2 3 4 5 6
frilled.cs.indiana.edu%
|
/* This is the solution to problem eleven of the first problem set. You
read from the user a string of digits and then make sure the resulting
string is at least 5 characters long. Once you have that, just print the
characters one by one separated by blank spaces. We just print the last
five, and we know we have at least five characters in the string because
we have taken care to pad it with a string of five blanks from the start */
public class Eleven {
public static void main(String[] args) {
// open a connection with the keyboard
ConsoleReader console = new ConsoleReader(System.in);
// tell the user to enter a number
System.out.print("Please enter a number between 0 and 99999: ");
// read the number the user types
String number = console.readLine();
// pad the number with five spaces
number = " " + number; // thus string has at least 5 characters
int i = number.length() - 1; // index of last char in string
// print the last five digits of the number
// note the order in which we print the chars and their indices
System.out.print(number.substring(i-4, i-3) + " ");
System.out.print(number.substring(i-3, i-2) + " ");
System.out.print(number.substring(i-2, i-1) + " ");
System.out.print(number.substring(i-1, i) + " ");
System.out.print(number.substring(i) + " \n");
}
}
| 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.
public class Twelve
{ 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));
}
}
|
/* This is the solution to problem twelve in the first problem set.
We first compute the constant for the conversion from degrees to radians
and then we repeatedly use the value of this constant, stored as x. */
public class Twelve {
public static void main(String[] args) {
double x = Math.PI / 180; // degreesToRadians constant
System.out.println
(" 0 degrees: " + Math.sin( 0 ) + " " + Math.cos( 0 ));
System.out.println
("30 degrees: " + Math.sin(30 * x) + " " + Math.cos(30 * x));
System.out.println
("45 degrees: " + Math.sin(45 * x) + " " + Math.cos(45 * x));
System.out.println
("60 degrees: " + Math.sin(60 * x) + " " + Math.cos(60 * x));
System.out.println
("90 degrees: " + Math.sin(90 * x) + " " + Math.cos(90 * x));
}
}
| 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%
|
/* This is the solution to problem thirteen in the first problem set.
You need ConsoleReader in the same directory, as explained in problem two,
before you can compile and run this program. */
public class Thirteen {
public static void main(String[] args) {
// open a keyboard connection
ConsoleReader console = new ConsoleReader(System.in);
// greet the user and ask for input
System.out.println("Hello, my name is Hal!");
System.out.println("What is your name?");
// get user input store it in String variable called name
String name = console.readLine();
// echo the data to the user and ask for request
System.out.println("Hello, " + name + ". I am glad to meet you.");
System.out.println("What would you like me to do?");
// get the request
String request = console.readLine();
// end the conversation politely
System.out.println("I am sorry, " + name + ". I cannot do that.");
}
}
| 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 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) + // sometimes not!
"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 so use:
// compute x, the difference between what you can and what you want
double x = efficiency * gallons - distance;
// avoid division by zero with this, can you see how?
double epsilon = 0.00001;
// make n 1 if x >= 0 and 0 otherwise
long n = Math.round( ( (x + Math.abs(x) ) * x + epsilon) /
( 2 * x * x + epsilon)
);
// why can't n be int? what do I need to do if I want it to be an int?
// report the correct answer
System.out.println("You will" +
answer.substring(0, 5 - 4 * (int)n) +
"make it.");
// why do I need to convert n from the long it is to an int here?
|
| |
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%
|
/* This is the solution to problem fourteen in the first problem set. You
need ConsoleReader in the same directory, as explained in problem two, to
compile and run this program. Note that the hint in the text is almost all
you need, minus one trick that makes sure that we can never divide by zero
and also produces an n of 1 when x is zero (avoiding division by zero too). */
public class Fourteen {
public static void main(String[] args) {
// get a connection to the keyboard
ConsoleReader console = new ConsoleReader(System.in);
// greet user, ask for input
System.out.println("Please enter number of gallons then press enter.");
// get number of gallons
double gallons = console.readDouble();
// ask for fuel efficiency
System.out.println("Please enter fuel efficiency in miles per gallon.");
// get it from user
double efficiency = console.readDouble();
// ask for desired distance
System.out.println("Please enter distance in miles you want to cover.");
// get distance
double distance = console.readDouble();
// prepare the answer
String answer = " not ";
// compute x, the difference between what you can and what you want
double x = efficiency * gallons - distance;
// avoid division by zero with this, can you see how?
double epsilon = 0.00001;
// make n 1 if x >= 0 and 0 otherwise
long n = Math.round( ( (x + Math.abs(x) ) * x + epsilon) /
( 2 * x * x + epsilon)
);
// why can't n be int? what do I need to do if I want it to be an int?
// report the correct answer
System.out.println("You will" +
answer.substring(0, 5 - 4 * (int)n) +
"make it.");
// why do I need to convert n from the long it is to an int here?
}
}
| 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.
Please enter the first time: 0900
Please enter the second time: 1730
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
|
| |
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%
|
/* This is the solution to problem fifteen in the first problem set.
You need to have ConsoleReader in a file in the same directory before
you can compile and run this. This problem adds 24 hours to the hours
difference to avoid negative values and takes the remainder with 24
to avoid values bigger than 24 (number of hours in a day). It also
transforms the hours into minutes to absorb possible negative values
from the difference between given minutes. */
public class Fifteen {
public static void main(String[] args) {
// get a connection to the keyboard
ConsoleReader console = new ConsoleReader(System.in);
// greet the user, ask for time
System.out.print("Please enter the first time: ");
// get the first time as a string (in military format)
String first = console.readLine();
// compute the number of hours from first two characters
int hours1 = Integer.parseInt(first.substring(0, 2));
// compute minutes from next two characters
int minutes1 = Integer.parseInt(first.substring(2, 4));
// ask for second time
System.out.print("Please enter the second time: ");
// get it
String second = console.readLine();
// compute hours, same as before
int hours2 = Integer.parseInt(second.substring(0, 2));
// compute minutes
int minutes2 = Integer.parseInt(second.substring(2, 4));
// compute the difference between hours, add 24 then divide
// by 24 and take the remainder to express the hour difference
int difHours = (hours2 + 24 - hours1) % 24;
// make these hours into minutes
int hrsToMins = difHours * 60;
// compute straight difference between given minutes, could be < 0
int difMins = minutes2 - minutes1;
// add this to total count of minutes
hrsToMins += difMins;
// report total count of minutes in hours and minutes
System.out.println(
hrsToMins / 60 + " hours " + hrsToMins % 60 + " minutes"
);
}
}
| 16. |
Run the following program, and explain the output you get.
public class Sixteen
{ 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 the solution to problem number sixteen in the first problem
set. The program attempts to use a different way of computing the average
of two numbers a and b by computing (1/a + 1/b)*a*b/2 in stages. It is OK
if the numbers entered are restricted to integers, but to correctly compute
at all stages in the program we need to circumvent integer division which
can result in a loss of precision. So we turn everything in float and all
is well after that. You need ConsoleReader as explained in problem 2. */
public class Sixteen {
public static void main(String[] args) {
ConsoleReader console = new ConsoleReader(System.in);
// one change below
float total = 0;
System.out.println("Please enter a positive number:");
// second change below
float x1 = (float)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:");
// third change below
float x2 = (float)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);
// that's it, three changes overall
}
}
| 17. |
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
|
| |
Here's a sample run with your program:
frilled.cs.indiana.edu%java Seventeen
* *
* *
*****
* *
* *
*****
*
*****
*
*****
*
*
*
*
*****
*
*
*
*
*****
***
* *
* *
* *
***
frilled.cs.indiana.edu%
|
/* This is the solution to problem seventeen in the first set of problems.
The text gives a suggestion that is enough to solve the problem, although
in this particular case you can't do it directly as suggested. But reading
the section on constants in the book you can come up with the following
absolutely obvious solution: */
public class Seventeen {
public static void main(String[] args) {
// define the letters as strings
final String LETTER_H = "* *\n* *\n*****\n* *\n* *\n\n";
final String LETTER_E = "*****\n* \n*****\n* \n*****\n\n";
final String LETTER_L = "* \n* \n* \n* \n*****\n\n";
final String LETTER_O = " *** \n* *\n* *\n* *\n *** \n\n";
// print them one after another
System.out.println(
LETTER_H + LETTER_E + LETTER_L + LETTER_L + LETTER_O
);
}
}
| 18. |
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. |
| |
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%
|
/* Solution to problem eighteen in the first problem set. Use ConsoleReader
from lab notes as explained in problem set 2. The trick here (as hinted in the
text) is to transform a number for a month in the position in the string where
the month name is starting, all names being made of the same length, and then
concatenated together in one final string. */
public class Eighteen {
public static void main(String[] args) {
String monthNames = "January " +
"February " +
"March " +
"April " +
"May " +
"June " +
"July " +
"August " +
"September " + // longest
"October " +
"November " +
"December " ;
// open a connection with the keyboard
ConsoleReader console = new ConsoleReader(System.in);
// greet the user, and ask for input
System.out.println("Please enter a month number from 1 to 12.");
// get month name
int month = console.readInt();
// report the name of the month
System.out.println(
monthNames.substring("September ".length() * (month-1),
"September ".length()*month));
// formula uses the length of the longest name
}
}
| 19. |
Change the password program
(textbook, page 80)
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 concatenate the initials
with the last four digits of the product.
|
| |
Here's a sample run with your program:
frilled.cs.indiana.edu%java Nineteen
Your password is: WJC0068
frilled.cs.indiana.edu%java Nineteen
Your password is: WJC9494
frilled.cs.indiana.edu%java Nineteen
Your password is: WJC2042
frilled.cs.indiana.edu%
|
/* This is solution to problem nineteen in the first set. We start from the
MakePassword problem on page 79 in the text. Following the hint the rest
becomes straightforward, including how you get the last four digits of the
product between the random number and the age, to concatenate to initials.
Note that you need to import the Random class from the java.util package. */
import java.util.Random; // need to import this to work with random numbers
public class Nineteen {
public static void main(String[] args) {
String firstName = "William";
String middleName = "Jefferson";
String lastName = "Clinton";
// extract initials
String initials =
firstName.substring (0, 1) +
middleName.substring(0, 1) +
lastName.substring (0, 1);
// append age
int age = 54;
int r = new Random().nextInt(1000);
// multiply age by random number
String product = (age * r) + "";
// concatenate initials with last four digits of product
String password = initials + product.substring(product.length() - 4);
System.out.println("Your password is: " + password);
}
}
Last updated: Jan 25, 2000 by Adrian German for A201