|
Spring Semester 2002 |
Here are examples of solutions, I skip the statement, I write only the sample solutions.
/***************************************************************************
This is the solution to the first problem in the first problem set: it
displays the first five powers of the first five numbers: 1, 2, 3, 4, 5.
This is a bit of an overkill, but that's only because the problem is so
elementary. Still, you should notice then that the third, fourth, and
fifth powers are being computed from previously calculated values.
****************************************************************************/
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
}
}
/******************************************************************************
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 and whose
source code is written below, then compile Two.java.
*******************************************************************************/
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);
}
}
/****************************************************************************
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.
******************************************************************************/
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.");
}
}
/**********************************************************************
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
***********************************************************************/
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);
}
}
/******************************************************************************
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.
*******************************************************************************/
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);
}
}
/*****************************************************************************
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).
******************************************************************************/
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");
}
}
/**********************************************************************
This is the solution to problem seven in the first problem set.
Need ConsoleReader in the same directory before you can compile
it (see problem 2). Formulas used are straightforward, easy.
***********************************************************************/
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.");
}
}
/*******************************************************************************
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.
********************************************************************************/
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));
}
}
/*************************************************************************
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.
**************************************************************************/
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);
}
}
/*************************************************************************
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.
**************************************************************************/
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);
}
}
/****************************************************************************
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.
*****************************************************************************/
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");
}
}
/**************************************************************************
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.
***************************************************************************/
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));
}
}
/**************************************************************************
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.
***************************************************************************/
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.");
}
}
/*******************************************************************************
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).
********************************************************************************/
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?
}
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
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.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
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"
);
}
}
/*******************************************************************************
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.
********************************************************************************/
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
}
}
/****************************************************************************
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:
*****************************************************************************/
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
);
}
}
/***********************************************************************************
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.
************************************************************************************/
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
}
}
/******************************************************************************
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.
Honestly: a better way to get random numbers is Math.random, but we stay
within the framework of the book for just this problem, from Chapter 2.
*******************************************************************************/
import java.util.Random; // need to import this to work with random numbers
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);
}
}
This last problem was from the previous administration.