SlideShare a Scribd company logo
1 of 48
Download to read offline
Prepared by R. Arthy, AP/IT 1
DEPARTMENT OF
INFORMATION TECHNOLOGY
CONCEPTUAL LEARNING
JAVA COURSE – ASSESSMENT
QUESTIONS
Prepared by
R. ARTHY, AP/IT
Prepared by R. Arthy, AP/IT 2
DEPARTMENT OF INFORMATION TECHNOLOGY
Conceptual Learning
Java Programming
Questions
Primitive data type
Exercise 1 — Shortfall
The following program uses primitive data type short:
class Shortfall
{
public static void main ( String[] args )
{
short value = 32;
System.out.println("A short: " + value);
}
}
value in this program is a variable—a name for a section of memory that holds data using a
particular data type. In this case value is the name for 16 bits of main memory that uses short
to represent an integer. (The next chapter says much more about variables.) This program
puts the value 32 into value. Then it writes out:
A short: 32
In other words, that line of the program examines the variable and writes out what it finds.
Your Job: Create a file called Shortfall.java that contains this program. (Copy and paste will
greatly speed this up.) Compile and run the program. Check what it writes onto the screen.
Now edit the program so that the 32 is changed to some other small number, say 356.
Compile and run the program. Everything should be fine.
Next change the number to 35000 and try to compile and run the program. This number is too
large to work with the data type short (in other words, it cannot be represented in 16 bits
using data type short.) What happens?
Now edit the program (don't change the 35000) so that the data type is int. Compile and run
the program. Is there a difference?
Exercise 2 — Double Jeopardy
The following program uses primitive data type double:
class DoubleJeopardy
Prepared by R. Arthy, AP/IT 3
{
public static void main ( String[] args )
{
double value = 32;
System.out.println("A double: " + value);
}
}
In this program, value is the name for a variable that uses the double data type to represent
floating point numbers. Recall that this data type uses 64 bits.
It is perfectly OK to use the name value in this and in the previous program. A variable name
helps describe what you want the program to do. It does not permanently reserve part of
computer memory for any particular use.
Compile and run the program. Does its output (what it puts on the screen) differ from the
output of the the previous exercise?
Change the 32 to 32.0 and see if that makes a difference when you compile and run the
program.
Now try to "break" the program. Look back in this chapter at the chart of primitive data types
and the range of values they can hold. Change the "32" to a value that is too big for double.
You may wish to use scientific notation for this.
Exercise 3 — Exponential Explosion
The following program also primitive data type double. This program computes and writes
out the value of exp( 32 ). This is the number "e" raised to the power 32. ("e" is the base of
natural logarithms. Don't worry much about this. The point of the program is not the math but
the floating point numbers.)
class ExponentialExplosion
{
public static void main ( String[] args )
{
double value = 32;
System.out.println("e to the power value: " + Math.exp( value ) );
}
}
Compile and run the program. Does it compile and run correctly? Now change the 32 to
larger and larger numbers until something goes wrong.
Exercise 4 — Character Assassination
The following program uses primitive data type char:
class CharAssassination
{
Prepared by R. Arthy, AP/IT 4
public static void main ( String[] args )
{
char ch = 'A' ;
System.out.println("A char: " + ch );
}
}
The variable ch is 16 bits of main memory that uses the char data type to represent characters.
The a bit pattern that represents 'A' is placed in it. The program writes:
A char: A
Do the following:
 Change the 'A' into 'Z' and compile and run.
 Change the 'A' into 'AA' and try to compile the program.
 Change the 'A' into ' ' and compile and run the program.
 Notice carefully: there is a single space between the two ' marks.
 Change the 'A' into '' and try to compile.
 Notice carefully: there is no character between the two ' marks.
 Change the 'A' into "A" and try to compile the program.
 (The double quotes " signify a String, which is something different from a
char).
Observe and explain what works and what does not work in the above.
Variable and Assignment
Exercise 1 — Payroll Program
Examine this program (from the chapter):
class Example
{
public static void main ( String[] args )
{
long hoursWorked = 40;
double payRate = 10.0, taxRate = 0.10;
System.out.println("Hours Worked: " + hoursWorked );
System.out.println("pay Amount : " + (hoursWorked * payRate) );
System.out.println("tax Amount : " + (hoursWorked * payRate * taxRate) );
}
}
Modify it so that each variable is declared by itself and is not initialized. Next write three
assignment statements to assign a value to each variable. Run the program; examine the
output.
Prepared by R. Arthy, AP/IT 5
Now let's break something: Remove one of the declarations from the program. Can you
compile it?
Now remove one of the initializations from the correct program. (For example, delete the
characters "= 40" from the first declaration. Try to compile and run the program. When is a
problem detected?
Exercise 2 — Value of a Quadradic
Say that you are interested in the value of the quadratic
3X2 -8X + 4
for several values of X. Write a program that has a double precision variable X. Assign a
value to it. Write statement that computes a value for the quadradic and stores the result in
another double precision variable. Finally write out the result, something like:
At X = 4.0 the value is 20.0
Run the program with several values for X (edit the program for each value of X) and
examine the result. Use values with decimal points, large values, small values, negative
values, and zero. Solve the equation with paper and pencil (use the quadradic formula.) The
quadradic should evaluate to zero at X = 2.0 and at X = 2/3. Try these values for X. Are the
results exactly correct?
Exercise 3 — Reassigning values to Variables
Modify the program in exercise 2 so that one run of the program will evaluate and write out
the value of the quadradic for three different values of X: 0.0, 2.0, and 4.0 (or any three
values of your choice.)
Write the program using only two variables, probably called x and value. Of course this
means that you will have to put different things in these variables in different places in the
program.
In writing the program make use of your editor's "copy" and "paste" functions to avoid re-
typing similar lines.
Expressions and Arithmetic Operator
Exercise 1 — Average Rain Fall
Write a program that averages the rain fall for three months, April, May, and June. Declare
and initialize a variable to the rain fall for each month. Compute the average, and write out
the results, something like:
Rainfall for April: 12
Rainfall for May : 14
Rainfall for June: 8
Average rainfall: 11.333333
Prepared by R. Arthy, AP/IT 6
To get the numerical values to line up use the tabulation character 't' as part of the character
string in the output statements. Check that your program prints the correct results. There is a
beginner's error lurking in this program too! Did you fall victim to it?
Exercise 2 — Trigonometry
To compute the sine of a double precision value use this method:
Math.sin( value )
The value is in radians (not degrees.) The cosine is computed using
Math.cos( value )
Again, value is in radians. Write a program that:
1. Computes the sine of 0.5236 radians and saves it in a variable.
2. Computes the cosine of 0.5236 radians and saves it in another variable.
3. Computes the square of each those two values (use the variables), adds the two
squares, and saves the result (in a third variable.)
4. Writes out the three variables.
The output statement should be something like:
System.out.println("sine: " + sinx + " cosine: " + cosx + " sum: " + sum );
Try a few other values besides 0.5236.
Exercise 3 — Degrees to Radians
It is sometimes hard to think in terms of radians; we would rather use degrees. Remember
(from those dark days of trigonometry class) that there are PI radians per 180 degrees. So to
convert an angle given in degrees to radians do this:
rad = degrees * Math.PI/180
Math.PI gives you an accurate value of PI.
Edit the previous program so that it does the same things, but the angle is 30 degrees (which
you will convert into radians.)
Object
Exercise 1 — Object Created at Run Time
Write a program that creates a String object that contains the string "Hello World" (or some
other favorite string). Assign the reference to the object to the reference variable str. Write the
characters of the object to the monitor:
Prepared by R. Arthy, AP/IT 7
System.out.println( str );
Run the program to confirm that it works as you expect. Now add a second reference variable
to the program, but don't create an object for it to refer to. Add a statement that uses the
second variable as if it held a valid object reference. Run the program, and see what happens:
System.out.println( secondVariable );
Play around with this program for a while to cement the notion in you head that an object and
its reference variable are different things, and that an object is created at run time.
Exercise 2 — String Length
Compile and run the StringDemo2 program from the chapter.
class StringDemo2
{
public static void main ( String[] args )
{
String str;
int len;
str = new String( "Elementary, my dear Watson!" );
len = str.length();
System.out.println("The length is: " + len );
}
}
Now change the String in various ways and observe the effect on the computed string length.
Add extra spaces on either side and in the middle of the string; add more punctuation; insert a
tab character (a real tab character, not just spaces). Note that the length of the string
"MMMMMM" is the same as "iiiiii". The length is the number of characters, not the actual
length of line it takes to print them.
Exercise 3 — A String Method that creates a new String
It is often useful to trim off extra spaces from both sides of a String. The trim() method of
String objects does that. It creates a new String object from an existing one, where the new
String object has all the characters of the original except that spaces and tabs have been
trimmed off the sides. The original String is not changed. For example, after the following
statements have executed
String first = new String(" In a Hole in the ground there lived a Hobbit. ")
String second;
second = first.trim();
Prepared by R. Arthy, AP/IT 8
there will be a second object, referred to by second, containing the characters
"In a Hole in the ground there lived a Hobbit."
Notice that internal extra spaces remain.
Write a program (or modify the previous one) that creates a String by calling the trim() of an
original String. Write both Strings to the monitor. Experiment with spaces and tabs to
determine exactly what is trimmed from the original.
Exercise 4 — Play with substring()
Compile and run the program from the chapter (repeated below) to confirm it works as
described. Then change the 8 to some other value and check if the result is what you expect.
class StringDemo3
{
public static void main ( String[] args )
{
String str = new String( "Golf is a good walk spoiled." ); // create the original object
String sub = str.substring(8); //create a new object from the original
System.out.println( sub );
}
}
String objects have another version of the substring() method that looks like this:
substring( int beginIndex, int endIndex )
This method creates a new String object based on the original object, but containing only the
characters that start at beginIndex and end at endIndex-1. It creates a completely new object;
the characters it contains are copies of those in the original object. For example, look at the
following:
String str = new String( "Golf is a good walk spoiled." ); // create the original object
String sub = str.substring(8, 19); //create a new object from the original
These create a new object (referenced by sub) containing the characters "a good walk" .
Modify your program so that it calls this two-parameter substring(). Experiment with the two
parameters to see how they work. Try the following:
1. Make both parameters the same value.
2. Make the first parameter 0, and the last parameter the index of the last character plus
one (28 for the example).
Prepared by R. Arthy, AP/IT 9
3. Instead of using a literal 28 in the above, use str.length() which will have the value 28.
4. Change the second parameter to 29 in the above.
5. Make the first parameter negative.
6. Reverse the order of the parameters.
Both parameters must be in the range 0 .. str.length() and the first must be less than or equal
to the second.
Good methods that deal sensibly with all possible input values, even those that make no
sense. For good security, programmers must expect that some users will maliciously try to
find parameters that cause problems or cause odd behavior that can somehow be exploited.
Input and Output
Exercise 1 — Area of a Circle
Write a program that calculates the area of a circle from its radius. The radius will be an
integer read in from the keyboard. The user dialog will look like this:
D:usersdefault>java CircleArea
Input the radius: 3
The radius is: 3 The area is: 28.274333882308138
You will need to use the constant PI which you get by using Math.PI.
Exercise 2 — Cents to Dollars
Write a program that reads in a number of cents. The program will write out the number of
dollars and cents, like this:
D:usersdefault>java Dollars
Input the cents:
324
That is 3 dollars and 24 cents.
(Use integer arithmetic and avoid floating point arithmetic. Review the integer remainder
operator % if you are unsure how to proceed.)
Exercise 3 — Correct Change
When cashiers make change they first try to "fit" dollars into the amount you get back, then
try to fit quarters (25 cent coins) into what is left over, they try to fit dimes (10 cent coins)
into what is now left over, then try to fit nickels (5 cent coins) into what is left, and finally are
left with a few odd cents. For example, say that your change is 163 cents:
 One dollar fits into 163, leaving 63 cents.
 Two quarters fit into 63 cents, leaving 13 cents.
 One dime fits into 13 cents, leaving 3 cents.
 No nickels are needed.
 Three cents are left.
Prepared by R. Arthy, AP/IT 10
Your change is : 1 dollar, two quarters, one dime, and three cents.
Write a program that reads how much change is due (in cents) and writes out that amount as
dollars, quarters, dimes, nickels, and pennies. Use integers for all variables and all arithmetic.
If you are stuck, do an example problem with paper and pencil.
Exercise 4 — Ohm's Law
Ohm's law relates the resistance of a electrical device (like a heater) to the electric current
flowing through the device and the voltage applied to it. The law is:
I = V/R
Here, V is the voltage (measured in volts), I is the current (measured in amps), and R is the
resistance (measured in ohms.) Write a program that asks the user for the voltage and the
resistance of a device. The program will then write out the current flowing through it. Use
floating point math.
Since V and R are integers (converted from user input) you must use a trick to do floating
point division. Change the equation to this:
I = (V + 0.0)/R
The math inside parentheses is done first. So V + 0.0 is done first, and since 0.0 is floating
point, so will be the result.
Floating Point
Exercise 1
Write a program that calculates the annual cost of running an appliance. The program asks the
user for the cost per kilowatt-hour and the number of kilowatt-hours the appliance uses in a
year:
Enter cost per kilowatt-hour in cents
8.42
Enter kilowatt-hours used per year
653
Annual cost: 54.9826
Exercise 2
When a brick is dropped from a tower, it falls faster and faster until it hits the earth. The
distance it travels is given by
d = (1/2)gt2
Here d is in feet, t is the time in seconds, and g is 32.174. Write a program that asks the user
for the number of seconds and then prints out the distance traveled.
Enter the number of seconds: 5.4
Distance: 469.096
Use the program to determine how far a brick falls in 100 seconds.
Prepared by R. Arthy, AP/IT 11
Exercise 3
The base 2 logarithm of a number is defined by:
log2 X = n if 2n
= X
For example
log2 32 = 5, because 25
= 32
log2 1024 = 10, because 210
= 1024
Write a program that inputs a number and outputs its base 2 logarithm. Use floating point
input. This problem would be easy, but the Math package does not have a base 2 logarithm
method. Instead you have to do this:
log2 X = (loge X) / (loge 2)
Here, loge X is the natural logarithm of X, which you can compute using
Math.log( X )
As usual, X is a double. The user enters floating point numbers:
Enter a double:
998.65
Base 2 log of 998.65 is 9.963835330516641
Exercise 4
The harmonic mean of two numbers is given by:
H = 2 / ( 1/X + 1/Y )
This is sometimes more useful than the more usual average of two numbers. Write a program
that inputs two numbers (as floating point) and writes out both the usual average (the
arithmetic mean) and the harmonic mean.
Enter X:
12
Enter Y:
16
Arithmetic mean: 14.0
Harmonic mean: 13.714285714285715
IF Statement
Exercise 1 — Discount Prices
During a sale at a store, a 10% discount is applied to purchases over $10.00. Write a program
that asks for the amount of a purchase, then calculates the discounted price. The purchase
amount will be input in cents (as an integer):
Enter amount of purchases:
2000
Discounted price: 1800
Prepared by R. Arthy, AP/IT 12
Use integer arithmetic throughout the program.
Exercise 2 — Order Checker
Bob's Discount Bolts charges the following prices:
 5 cents per bolt
 3 cents per nut
 1 cent per washer
Write a program that asks the user for the number of bolts, nuts, and washers in their
purchase and then calculates and prints out the total. As an added feature, the program checks
the order. A correct order must have at least as many nuts as bolts and at least twice as many
washers as blots, otherwise the order has an error. For an error the program writes out "Check
the Order: too few nuts" or "Check the Order: too few washers" as appropriate. Both error
messages are written if the order has both errors. If there are no errors the program writes out
"Order is OK." In all cases the total price in cents (of the specified number of items) is
written out.
Number of bolts: 12
Number of nuts: 8
Number of washers: 24
Check the Order: too few nuts
Total cost: 108
Use constants for the unit cost of each item. In other words, declare constants such as final
int boltPrice = 5;.
Exercise 3 — Last Chance Gas
Al's Last Chance Gas station sits on Route 190 on the edge of Death Valley. There is no other
gas station for 200 miles. Write a program to help drivers decide if they need gas. The
program asks for:
 The capacity of the gas tank, in gallons.
 The indication of the gas gauge in percent (full= 100, three quarters full = 75, and so
on).
 The miles per gallon of the car.
The program then writes out "Get Gas" or "Safe to Proceed" depending on if the car can cross
the 200 miles with the gas remaining in the tank.
Tank capacity:
12
Gage reading:
50
Miles per gallon:
30
Prepared by R. Arthy, AP/IT 13
Get Gas!
Use integers for all input and all arithmetic.
Exercise 4 — Pie Eating Contest
At the State Fair Pie Eating Contest all contestants in the heavyweight division must weigh
within 30 pounds of 250 pounds. Write a program that asks for a contestant's weight and then
says if the contestant is allowed in the contest.
Exercise 5 — Ground Beef Value Calculator
Different packages of ground beef have different percentages of fat and different costs per
pound. Write a program that asks the user for:
1. The price per pound of package "A"
2. The percent lean in package "A"
3. The price per pound of package "B"
4. The percent lean in package "B"
The program then calculates the cost per pound of lean (non-fat) beef for each package and
writes out which is the best value.
Price per pound package A:
2.89
Percent lean package A:
85
Price per pound package B:
3.49
Percent lean package B:
93
Package A cost per pound of lean:3.4
Package B cost per pound of lean:3.752688
Package A is the best value
Assume that the two packages will not come out equal in value.
Exercise 5 — Y2K Problem Detector
Write a program that asks a user for their birth year encoded as two digits (like "62") and for
the current year, also encoded as two digits (like "99"). The program is to correctly write out
the users age in years.
Year of Birth: 62
Current year: 99
Your age: 37
The program will have to determine when a two digit value such as "62" corresponds to a
year in the 20th
century ("1962") or the 21st
century. Here is another run of the program,
where "00" is taken to mean the year 2000:
Year of Birth: 62
Prepared by R. Arthy, AP/IT 14
Current year: 00
Your age: 38
Assume that ages are not negative. Another run of the program:
Year of Birth: 27
Current year: 07
Your age: 80
In the following run, the age of the person could be 6 or 106 depending on the assumptions.
Assume that the age will always be less than or equal to 100.
Year of Birth: 01
Current year: 07
Your age: 6
Exercise 6 — Wind Chill Index
(You will need to include java.Math.* and use floating point input for this exercise.)
The wind chill index (WCI) is calculated from the wind speed v in miles per hour and the
temperature t in Fahrenheit. Three formulas are used, depending on the wind speed:
if (0 <= v <= 4) then WCI = t
if (v >=45) then WCI = 1.6t - 55
otherwise, WCI = 91.4 + (91.4 - t)(0.0203v - 0.304(v)1/2
- 0.474)
To calculate (v)1/2
use Math.sqrt( double ).
Exercise 7 — Your Age in Seconds
Write a program that asks for your age in years, months, and days and writes out your age in
seconds. Do this by calculating the number of total days you have been alive, then multiply
this by the number of hours per day (24), the number of minutes per hour (60), and the
number of seconds per minute (60). Assume that there are 365 days per year (ignore leap
years). But correctly take account of the different number of days in different months. If the
user enters 5 for the number of months, add up the number of days in the first 5 months: 31
+ 28 + 31 + 30 + 31
A human lifespan is about 2.5 billion seconds (2.5 billion heart-beats).
Exercise 8 — Matinee Movie Tickets
Write a program that determines the price of a movie ticket (similar to the one in the chapter).
The program asks for the customer's age and for the time on a 24-hour clock (where noon is
1200 and 4:30PM is 1630). The normal adult ticket price is $8.00, however the adult matinee
price is $5.00. Adults are those over 13 years. The normal children's ticket price is $4.00,
however the children's matinee price is $2.00. Assume that a matinee starts at any time earlier
than 5pm (1700).
Get the information from the user and then use nested if statements to determine the ticket
price. It is usually a good idea to separate the "information gathering phase" (asking the user
for age and time) from the "processing phase" of a program (deciding on the ticket price).
Prepared by R. Arthy, AP/IT 15
There are many ways in which the if statements can be nested. Sketch out a flowchart as
you design your program.
Exercise 9 — Midnight Madness
Sales of movie tickets has been dropping! In an effort to attract more viewers, the theater has
started a new policy charging $4.00 for all tickets sold after 2200 (10PM). However, no
children may purchase tickets after that time. Add logic to the program of exercise 8 to
implement the new policy.
Branch IF
Exercise 1 — Internet Delicatessen
You have been asked to write a program for the Sam and Ella Delicatessen. The program
takes deli orders from the Internet. It asks for the item, its price in cents, and if overnight
shipping is wanted. The program writes out the order and the charges. Regular shipping for
items under $10 is $2.00; for items $10 or more shipping is $3.00. For overnight delivery add
$5.00.
Enter the item: Tuna Salad
Enter the price: 450
Overnight delivery (0==no, 1==yes): 1
Invoice:
Tuna Salad 4.50
shipping 7.00
total 11.50
(Use our console I/O methods. A real Internet order form would use different I/O methods,
but ignore this.)
Exercise 2 — Steam Engine Efficiency
The maximum possible efficiency of a steam engine depends on the temperature of the steam
in the boiler and the temperature of the outside air:
efficiency = 1 - Tair / Tsteam
where Tair is the air temperature and Tsteam is the steam temperature. The temperatures
are give in degrees above absolute zero. Normal air temperature is about 300o
K. Boiling is
373o
K. Write a program that asks the user for the air temperature and the steam temperature
and writes out the maximum possible efficiency of a steam engine. However, if the steam
temperature is less than 373o
K there is no steam, so the efficiency is zero.
Use integer or floating point input, but do the calculations in floating point.
Exercise 3 — Microwave Oven
A microwave oven manufacturer recommends that when heating two items, add 50% to the
heating time, and when heating three items double the heating time. Heating more than three
items at once is not recommended.
Prepared by R. Arthy, AP/IT 16
Write a program that asks the user for the number of items and the single-item heating time.
The program then writes out the recommended heating time.
Hint: do this with four successive single-branch if statements each of which tests for one of
the four cases: 1 item, 2 items, 3 items, more than three items. Look at the sports car purchase
program in the chapter to see how to do this, if you are stuck.
Exercise 4 — Fantasy Game
In a new role-playing fantasy game players must design their character by picking a point
value for each of three characteristics:
 Strength, from 1 to 10
 Health, from 1 to 10
 Luck, from 1 to 10
Write a program that asks for a name for the character and asks for the point value of for each
of the three characteristics. However, the total points must be less than 15. If the total exceeds
15, then 5 points are assigned to each characteristic
Welcome to Yertle's Quest
Enter the name of your character:
Chortle
Enter strength (1-10):
8
Enter health (1-10):
4
Enter luck (1-10):
6
You have give your character too many points! Default values have been assigned:
Chortle, strength: 5, health: 5, luck: 5
(This user interface could get much more complicated. You might want to implement some of
your own ideas.)
Boolean Expression
Exercise 1 — Check Charge
A bank has the following rule: if a customer has more than $1000 dollars in their checking
account or more than $1500 dollars in their savings account, then there is no service charge
for writing checks. Otherwise there is a $0.15 charge per check. Write a program that asks for
the balance in each account and then writes out the service charge.
Exercise 2 — Tire Pressure
The front tires of a car should both have the same pressure. Also, the rear tires of a car should
both have the same pressure (but not necessarily the same pressure as the front tires.) Write a
Prepared by R. Arthy, AP/IT 17
program that reads in the pressure of the four tires and writes a message that says if the
inflation is OK or not.
Input right front pressure
38
Input left front pressure
38
Input right rear pressure
42
Input left rear pressure
42
Inflation is OK
Exercise 3 — More Tire Pressure
Its not enough that the pressures are the same in the tires, but the pressures must also be
within range. Modify the program in exercise 1 so that it also checks that each tire has a
pressure between 35 and 45. If a tire is out of range, write out an error message immediately,
but continue inputting values and processing them:
Input right front pressure
32
Warning: pressure is out of range
Input left front pressure
32
Warning: pressure is out of range
Input right rear pressure
42
Input left rear pressure
42
Inflation is BAD
If there have been any warnings, write out a final error message. (To do this, declare a
boolean variable goodPressure that is initialized to true but is changed to false when an out of
range tire is first found.)
Exercise 4 — The Pressure is Building
Tires don't have to have exactly the same pressure. Modify the program for exercise 2 so that
the front tires can be within 3 psi of each other, and the rear tires can be within 3 psi of each
other.
Input right front pressure
35
Input left front pressure
37
Input right rear pressure
41
Input left rear pressure
Prepared by R. Arthy, AP/IT 18
44
Inflation is OK
Looping
Exercise 1
Write a program that asks the user for a starting value and an ending value and then writes all
the integers (inclusive) between those two values.
Enter Start:
5
Enter End:
9
5
6
7
8
9
Exercise 2
Write a program that asks the user to enter a word. The program will then repeat word for as
many times as it has characters:
Enter a word:
Hello
Hello
Hello
Hello
Hello
Hello
To do this you will need to use the length() method that counts the number of characters in a
string:
String inputString;
int times;
. . . .
times = inputString.length()
Prepared by R. Arthy, AP/IT 19
Exercise 3
Write a program that asks the user to enter two words. The program then prints out both
words on one line. The words will be separated by enought dots so that the total line length is
30:
Enter first word:
turtle
Enter second word
153
turtle....................153
This could be used as part of an index for a book. To print out the dots, use
System.out.print(".") inside a loop body.
Methods and Messages
Exercise 1 — Adding up Integers
Write a program that adds up integers that the user enters. First the programs asks how many
numbers will be added up. Then the program prompts the user for each number. Finally it
prints the sum.
How many integers will be added:
5
Enter an integer:
3
Enter an integer:
4
Enter an integer:
-4
Enter an integer:
-3
Enter an integer:
7
The sum is 7
Be careful not to add the number of integers (in the example, 5) into the sum.
Exercise 2
Write a program that computes the following sum:
sum = 1.0/1 + 1.0/2 + 1.0/3 + 1.0/4 + 1.0/5 + .... + 1.0/N
N is an integer limit that the user enters.
Enter N
4
Sum is: 2.08333333333
Prepared by R. Arthy, AP/IT 20
Exercise 3
Write a program that computes the standard deviation of a set of floating point numbers that
the user enters. First the user says how many numbers N are to follow. Then the program asks
for and reads in each floating point number. Finally it writes out the standard deviation. The
standard deviation of a set of numbers Xi is:
SD = Math.sqrt( avgSquare - avg2
)
Here, avg is the average of the N numbers, and avg2
is its square.
avgSquare is the average of Xi * Xi. In other words, this is the average of the squared
value of each floating point number.
For example, if N = 4, say the numbers were:
Xi Xi * Xi
2.0 4.0
3.0 9.0
1.0 1.0
2.0 4.0
sum 8.0 18.0
Now:
avg = 8.0/4 = 2.0
avg2
= 4.0
avgSquare = 18.0/4 = 4.5
SD = Math.sqrt( 4.5 - 4.0 ) = Math.sqrt( .5 ) = 0.7071067812
To do this you will need to do several things inside the loop body for each floating point
value as it comes in: add it to a sum, square it and add it to a sum of squares. Then after the
loop is finished apply the formula.
Inheritance
Exercise 1 — Jet Lag Calculator
How many days of rest do you need to recover from jet lag? The International Civil Avaiation
Organization has a fomula for this:
1. Hours = number of hours of travel
2. Zones = number of time zones crossed
3. Depart =
o 0, for departures between 8AM and noon
o 1, for departures between noon and 6PM
o 3, for departures between 6PM and 10PM
Prepared by R. Arthy, AP/IT 21
o 4, for departures between 10PM and 1AM
o 5, for departures between 1AM and 8AM
4. Arrive =
o 4, for arrivals between 8AM and noon
o 2, for arrivals between noon and 6PM
o 0, for arrivals between 6PM and 10PM
o 1, for arrivals between 10PM and 1AM
o 3, for arrivals between 1AM and 8AM
The number of days you need to recover is:
days of recovery = (Hours/2 + (Zones-3) + Depart + Arrive)/10
For example, say that you are flying from New York Kennedy Airport to London Heathrow.
Your flight leaves at 7AM (New York time) and arrives at 7PM (London time).
1. Hours = 7 (London time is New York time + 5)
2. Zones = 4
3. Depart = 5
4. Arrive = 0
days of recovery = (7/2 + (4-3) + 5 + 0)/10 = (3.5 + 1 + 5 + 0)/10 = 9.5/10 = 0.95 days
Write a program that asks the user for the number of hours of travel, the number of time
zones crossed, the departure time, and the arrival time and then calculates the number of days
needed for recovery. Let the user enter time using a 24 hour clock (so 6PM is 18).
(Formula from Darrell Huff, How to Figure It, Norton, 1996.
Exercise 2 — Adding up Squares and Cubes
Write a program that adds up the squares and adds up the cubes of integers from 1 to N,
where N is entered by the user:
Upper Limit:
5
The sum of Squares is 55
The sum of Cubes is 225
Do this by using just one loop that generates the integers. Of course, if you really needed to
calculate these sums you would use the appropriate formulas:
12
+ 22
+ 32
+ ... + n2
= n(n+1)(2n+1)/6
13
+ 23
+ 33
+ ... + n3
= n2
(n+1)2
/4
Add these formulas to your program and print out their results as well as that of the explicit
summations.
Prepared by R. Arthy, AP/IT 22
Exercise 3 — Power of a number
Write a program that computes XN
where X is a floating point number and N is a positive
integer. The program informs the user that N must be positive if the user enters a negative
value. Of course,
XN
= X * X * X * ... * X <-- N of these
The user dialog will look something like this:
Enter X
1.3
Enter N
5
1.3 raised to the power 5 is: 3.71293
-------
Enter X
5.6
Enter N
-3
N must be a positive integer.
Exercise 4 — Wedge of Stars
Write a program that writes a wedge of stars. The user enters the initial number of stars, and
the program writes out lines of stars. Each line has one few star than the previous line:
Initial number of stars:
7
*******
******
*****
****
***
**
*
Exercise 5 — Pine Tree
Write a program that writes a tree made of stars on the terminal:
*
***
*****
*******
*********
***********
*************
***************
Prepared by R. Arthy, AP/IT 23
***
***
***
Exercise 5 — Wallpaper Calculator
Write a program that calculates how many rolls of wallpaper you need for a room. Assume
that the room is a rectangular prism (the usual shape) of specified width, height, and length.
Only the walls will be covered with wallpaper. The room may have several openings
(windows, doors) which will not be covered. Wallpaper comes in rolls. A single roll of
wallpaper is 27 inches wide and 4.5 yards long. Wallpaper is applied to the walls in vertical
strips.
Ask the user for the dimensions of the room and the number of openings. Then ask for the
dimensions of each opening. Calculate and display the number of full rolls of wallpaper
needed.
A quick approximation is to calculate the area of the room to be covered (the area of the walls
minus the area of the openings), then divide that by the area covered by a roll of wallpaper.
Round up to the nearest integer number of rolls.
A more accurate calculation allows for walls with a width that is not an integer multiple of
the standard width of 27 inches. The last strip of wallpaper for a wall may have to be cut from
from a standard width strip, wasting the rest of that strip.
Exercise 6 — Float Factorial
Change the factorial program so that fact is data type double instead of long. Keep the
loop control variable N of type long.
Try to figure out how much larger N can be with this program. Of course, since data type
double is not precise there will be accuracy errors with large N. For some applications
(such as number theory or code breaking) this would not be acceptable.
To study this problem further, modify the program to calculate N! / (N-1)!. Of course,
this should be N. But if you first calculate the factorials, and then divide them, you will only
get an approximation to N.
Exercise 7 — Permutaions
The formula for the number of permutations of N objects taken R at a time without repitition
is
N!/(N-R)!
Modify the original factorial program (that uses data type long) so that it calculates this
value. Ask the user for both N and R where both must be zero or positive and R must be less
than or equal to N. Write error messages for incorrect values.
Of course, it would not be sensible to separately calculate N! and (N-R)! and then to
divide. Design your program so that it does the minimum number of multiplications needed.
Prepared by R. Arthy, AP/IT 24
Packages
Exercise 1 — Adding Integers
AddUpNumbers, the program that adds integers from the user could be improved. In some
situations it would not be correct to say that the sum of integers is zero when the user, in fact,
entered no integers. (For example, teachers sometimes distinguish between an assignment
that got zero points and an assignment that was not turned in.) Modify the program so that it
writes a message if the first value entered by the user is the sentinal value of zero. Otherwise,
the program proceeds as before.
Enter first integer (enter 0 to quit): 0
No integers were entered.
bye
Enter first integer (enter 0 to quit): 3
Enter an integer (or 0 to quit): -3
Enter an integer (or 0 to quit): 0
Sum of the integers: 0
bye
Exercise 2 — Miles per Gallon
Write a program that calculates miles per gallon for a list of cars. The data for each car
consists of initial odometer reading, final odometer reading, and number of gallons of gas.
The user signals that there are no more cars by entering a negative initial odometer reading.
Miles Per Gallon Program
Initial miles:
15000
Final miles:
15250
Gallons
10
Miles per Gallon: 25.0
Initial miles:
107000
Final miles:
107450
Gallons
15
Miles per Gallon: 30.0
Initial miles:
-1
bye
Prepared by R. Arthy, AP/IT 25
Exercise 3 — In-range Adder
Write a program that asks the user for the low and high integer in a range of integers. The
program then asks the user for integers to be added up. The program computes two sums:
 The sum of integers that are in the range (inclusive),
 and the sum of integers that are outside of the range.
The user signals the end of input with a 0.
In-range Adder
Low end of range:
20
High end of range:
50
Enter data:
21
Enter data:
60
Enter data:
49
Enter data:
30
Enter data:
91
Enter data:
0
Sum of in range values: 100
Sum of out of range values: 151
Exercise 4 — Shipping Cost Calculator
A mail order company charges $3.00 for handling, free shipping for orders 10 pounds or less,
plus $0.25 for each pound over 10. Write a program that repeatedly asks the user for the
weight of an order, then writes out the shipping charge. The program stops when a weight of
zero or less is entered.
Weight of Order:
5
Shipping Cost: $3.00
Weight of Order
20
Shipping Cost: $5.50
Weight of Order
0
bye
Prepared by R. Arthy, AP/IT 26
Exercise 5 — Area of Rectangles
A computer aided design program expects users to enter the coordinates two corners for each
of several of rectangles (see diagram.) The sides of the rectangles are assumed to be parallel
to the X and Y axes. The coordinates of each corner is entered as a pair of integers, first the X
coordinate and then the Y coordinate. The origin of the coordinate system (0,0) is in the upper
left, so Y increases going downward, and X increases to the right.
For each rectangle, the program calculates and writes out the height, the width, and the area
of the rectangle. The two corners entered for each rectangle must be diagonally opposite
(upper left and lower right, or upper right and lower left), but which choice is made for each
rectangle is up to the user. The user can enter the corners in any order. Height and width are
always positive (the program will have to adjust its calculations so that this is true.)
The program ends gracefully when the user enters corners which cannot be those of a
rectangle (either the height is zero, the width is zero, or both.)
Computer Aided Design Program
First corner X coordinate:
100
First corner Y coordinate:
100
Second corner X coordinate:
250
Second corner Y coordinate
200
Width: 150 Height: 100 Area: 15000
First corner X coordinate:
250
First corner Y coordinate:
200
Second corner X coordinate:
100
Second corner Y coordinate
Prepared by R. Arthy, AP/IT 27
100
Width: 150 Height: 100 Area: 15000
First corner X coordinate:
100
First corner Y coordinate:
200
Second corner X coordinate:
250
Second corner Y coordinate
100
Width: 150 Height: 100 Area: 15000
First corner X coordinate:
100
First corner Y coordinate:
100
Second corner X coordinate:
100
Second corner Y coordinate
100
Width: 0 Height: 0 Area: 0
finished
Exercise 6 — Login Simulator
Write a program that simulates the "login" process of a computer. A loop continuously asks
the user for their user name and password. Assume that each is a single word. If the user
name and password match one of the correct pairs, allow the user to log on (actually: just
print a simulated message). A logged-on user has a priority from 1 (low) to 5 (high).
Otherwise print a failure message. If the user name is "quit" with a password "exit", exit the
loop and print a final message.
Use a if else if structure nested inside a while loop to do this. Use the equals()
method of String to compare user data with allowed user names and passwords. User names
and passwords are case sensitive. "Hard code" the user names and passwords (that it, make
them string literals that are part of each if statement. Here are some sample users and
passwords:
 user name; password; priority
 joy; sun; 4
 gates; monopoly; 1
 jobs; apple; 3
 root; secret; 5
Here is a sample run of the program:
User Name: gates
Prepared by R. Arthy, AP/IT 28
Password : money
Logon failed
User Name: gates
Password : monopoly
You have logged on with priority 1
User Name: hacker
Password : crack
Logon failed
User Name: jobs
Password : apple
You have logged on with priority 3
User Name: quit
Password : exit
System shutting down.
Bye.
The if else if structure is really nothing new; it is a way of indenting your program to
emphasize that a choice is being made out of a list of options. Here is a code excerpt that does
one of four things, depending on whether choice is 0, 1, 2, or 3. The final else handles
the situation where choice is out of range:
choice = scan.nextInt();
if ( choice==0 )
{
// code for choice 0
}
else if ( choice==1 )
{
// code for choice 1
}
else if ( choice==2 )
{
// code for choice 2
}
else if ( choice==3 )
{
// code for choice 3
}
else
{
// error handling
}
Exception Handling
Prepared by R. Arthy, AP/IT 29
Exercise 1 — Modified Million Dollars
Modify the DollarsAfterForty program in the chapter so that it asks the user for the interest
rate, the initial investment, and the annual contribution. The program prints out the current
value of the investment at the end of each year and continues until it reaches or exceeds one
million dollars.
Exercise 2 — Credit Card Bill
Say that you owe the credit card company $1000.00. The company charges you 1.5% per
month on the unpaid balance. You have decided to stop using the card and to pay off the debt
by making a monthly payment of N dollars a month. Write a program that asks for the
monthly payment, then writes out the balance and total payments so far for every succeeding
month until the balance is zero or less.
Enter the monthly payment:
100
Month: 1 balance: 915.0 total payments: 100.0
Month: 2 balance: 828.725 total payments: 200.0
Month: 3 balance: 741.155875 total payments: 300.0
Month: 4 balance: 652.273213125 total payments: 400.0
Month: 5 balance: 562.057311321875 total payments: 500.0
Month: 6 balance: 470.4881709917031 total payments: 600.0
Month: 7 balance: 377.54549355657866 total payments: 700.0
Month: 8 balance: 283.20867595992735 total payments: 800.0
Month: 9 balance: 187.4568060993263 total payments: 900.0
Month: 10 balance: 90.26865819081618 total payments: 1000.0
Month: 11 balance: -8.377311936321576 total payments: 1100.0
For each month, calculate the interest due on the unpaid balance. Then calculate the new
balance by adding the interest and subtracting the payment.
Improved Program: Have the program prompt for the beginning balance, the monthly
interest, and the payment amount. Also, when the balance falls below the amount of the
monthly payment, write out the final payment that will bring the balance to exactly zero.
Further Improved Program: The output of the program is somewhat ugly, with the
columns not aligned and too many digits printed in the decimal fractions. This can be
improved. Place the following lines in the appropriate places in your program. You will need
to modify the last line to fit with the rest of your program.
import java.text.*;
DecimalFormat numform = new DecimalFormat();
System.out.print( "balance: " + numform.format(balance) );
For details about how this works, see Chapter 24.
Exercise 3 — Drug Potency
A certain drug looses 4% of its effectiveness every month it is in storage. When its
effectiveness is below 50% it is considered expired and must be discarded. Write a program
that determines how many months the drug can remain in storage.
month: 0 effectiveness: 100.0
Prepared by R. Arthy, AP/IT 30
month: 1 effectiveness: 96.0
month: 2 effectiveness: 92.16
month: 3 effectiveness: 88.47359999999999
month: 4 effectiveness: 84.93465599999999
month: 5 effectiveness: 81.53726975999999
month: 6 effectiveness: 78.27577896959998
month: 7 effectiveness: 75.14474781081599
month: 8 effectiveness: 72.13895789838334
month: 9 effectiveness: 69.253399582448
month: 10 effectiveness: 66.48326359915008
month: 11 effectiveness: 63.82393305518407
month: 12 effectiveness: 61.27097573297671
month: 13 effectiveness: 58.82013670365764
month: 14 effectiveness: 56.46733123551133
month: 15 effectiveness: 54.20863798609088
month: 16 effectiveness: 52.04029246664724
month: 17 effectiveness: 49.95868076798135 DISCARDED
Exercise 4 — ex
One of the more amazing facts from calculus is that the following sum gets closer and closer
to the value ex
the more terms you add in:
e x
= 1 + x + x 2
/2! + x 3
/3! + x 4
/4! + x 5
/5! + x 6
/6! + . . . .
Remember that n! means n factorial, n*(n-1)*(n-2)* ... *1. For example, if x is 2
then
e2
= 1 + 2 + 22
/2! + 23
/3! + 24
/4! + 25
/5! . . . .
e2
= 1 + 2 + 4/2 + 8/6 + 16/24 + 32/120 + . . . .
e2
= 1 + 2 + 2 + 1.3333 + 0.6666 + 0.2666 + . . . .
e2
~ 7.266
More exactly, e2
= 7.38907...
Write a program that asks the user to enter x, then calculates ex
using a loop to add up
successive terms until the current term is less than 1.0E-12. Then write out the value
Math.exp(x) to see how your value compares.
To do this program sensibly, the loop will add in a term each iteration.
sum = sum + term;
Look carefully at the first equation for ex
. Notice that each term in the series is:
x N
/N!
for some N. This is the same as:
x(N-1)
/(N-1)! * x/N
Prepared by R. Arthy, AP/IT 31
This is the previous term times x/N. So each iteration of the loop merely has to multiply the
previous term by x/N and add it to the accumulating sum.
Don't let the math scare you away! This is actually a fairly easy program, and is typical of a
type of calculation that computers are often used for.
Enter x:
2
n:1 term: 2.0 sum: 3.0
n:2 term: 2.0 sum: 5.0
n:3 term: 1.3333333333333333 sum: 6.333333333333333
n:4 term: 0.6666666666666666 sum: 7.0
n:5 term: 0.26666666666666666 sum: 7.266666666666667
n:6 term: 0.08888888888888889 sum: 7.355555555555555
n:7 term: 0.025396825396825397 sum: 7.3809523809523805
n:8 term: 0.006349206349206349 sum: 7.387301587301587
n:9 term: 0.0014109347442680777 sum: 7.3887125220458545
n:10 term: 2.8218694885361555E-4 sum: 7.388994708994708
n:11 term: 5.130671797338464E-5 sum: 7.389046015712681
n:12 term: 8.551119662230774E-6 sum: 7.3890545668323435
n:13 term: 1.3155568711124268E-6 sum: 7.389055882389215
n:14 term: 1.8793669587320383E-7 sum: 7.3890560703259105
n:15 term: 2.5058226116427178E-8 sum: 7.389056095384136
n:16 term: 3.1322782645533972E-9 sum: 7.389056098516415
n:17 term: 3.6850332524157613E-10 sum: 7.389056098884918
n:18 term: 4.094481391573068E-11 sum: 7.389056098925863
n:19 term: 4.309980412182177E-12 sum: 7.3890560989301735
n:20 term: 4.309980412182177E-13 sum: 7.389056098930604
my e^x: 7.389056098930604
real e^x: 7.38905609893065
Exercise 4 — 1/B by Newton's Method
Another amazing fact from calculus is that you can calculate 1/B without doing division.
(Assume that B is a positive real number.)
Say that x is your first guess for the value 1/B. Then your guess can be improved by using
the formula:
x' = x*(2-B*x)
Of course, now that guess can be further improved by using the same formula. This formula
is yet another application of Newton's Method.
For example, say that B is 4.0. You want to calculate 1/4. Say that your first guess for this
value is 0.1 ; then an improved guess is:
x' = 0.1 * (2 - 4*0.1) = 0.1 * (2 - .4) = 0.1*(1.6) = 0.16
The next estimate is:
x' = 0.16 * (2 - 4*0.16) = 0.16 * (2 - 0.64) = 0.16 * 1.36 = 0.2176
A further improvement is:
Prepared by R. Arthy, AP/IT 32
x' = 0.2176 * (2 - 4*0.2176) = 0.2176 * (2 - 0.8704) = 0.2176 * 1.1296 = 0.24580096
Repeat the formula to further improve the guess.
Write a program that asks the user for B and then writes out 1/B without using a division.
You will need to think of an appropriate ending condition for the loop that calculates 1/B.
Unfortunately, the first guess for this method must be between zero and the true value of
1/B. It sounds like you need division to make the first guess, but this can be avoided by
always starting with a hard-coded (a constant that is part of the program) very tiny first guess.
For very large values of B your first guess might not be tiny enough, because 1/B is so small.
Protect your code with an if statement that checks if B is too large for the program to handle.
If the first guess is hard-coded, then you know the maximum value for B.
Of course, 1/0 is not defined, so test for this, too.
Exercise 5 — Hailstone Numbers
Write a program that asks the user for a positive integer N and then calculates a new value for
N based on whether it is even or odd:
if N is even, the new N is N/2. (Use integer division.)
if N is odd, the new N is 3*N + 1.
Repeat with each new N until you reach the value 1.
For example, say the initial value is 12. Then the successive values are:
12 (even, next value is 12/2)
6 (even, next value is 6/2)
3 (odd, next value is 3*3+1)
10 (even, next value is 10/2)
5 (odd, next value is 3*5+1)
16 (even, next value is 16/2)
8 (even, next value is 8/2)
4 (even, next value is 4/2)
2 (even, next value is 2/2)
1 (stop calculation)
The sequence of integers is called a hailstone series because the integers increase and
decrease, sometimes many times, before eventually reaching 1. (This is supposed to be like
hailstones blowing up and down in a storm before reaching the ground.)
For all integers that have been tested (up to 1048
) the series eventually does reach 1. But no
one knows for sure if this is true for all integers.
Additional Things to Calculate: In addition to calculating and printing out the sequence for
a particular initial N, keep track of the length of the sequence and the maximum integer in the
sequence and print them out when the sequence reaches its end.
A variation on this program is to generate each sequence for initial numbers from 1 to 1000,
and to determine the length and starting number of the longest of those sequences. You
Prepared by R. Arthy, AP/IT 33
probably don't want to print out each sequence, just keep track of each length and compare it
to the current maximum.
Hard: Are there any integers from 1 to 1000 that are not in any hailstone sequence other than
the one they start? To write a sensible program that determines this, you will need to use an
array, which is the subject of chapter 46. You may wish to return to this problem after you
have covered that chapter.
Note: it is natural to investigate sequences that start with initial numbers in the millions or
higher. The terms of these sequences get very large; larger than can be held in an int
variable. Use data type long to avoid these problems. That will work for initial values up to
at least five billion.
Interface
Exercise 1 — Guessing Game
Write a program that implements a guessing game. This is a "classic" program, frequently
assigned in beginning CS classes.
The program picks a random number from 1 to 10. Now the user gets three guesses. As soon
as the user enters the correct number the program writes a winning message and exits. If the
user fails to enter the correct number in three guesses, the program writes a failure message
and exits.
Use methods of the Random class. Here are two example runs of the program:
C:>java GuessingGame
I am thinking of a number from 1 to 10.
You must guess what it is in three tries.
Enter a guess:
4
wrong
8
RIGHT!
You have won the game.
C:>java GuessingGame
I am thinking of a number from 1 to 10.
You must guess what it is in three tries.
Enter a guess:
1
wrong
5
wrong
9
wrong
The correct number was 7.
You have lost the game.
Prepared by R. Arthy, AP/IT 34
Exercise 2 — Improved Guessing Game
Write a more complicated guessing game, similar to the one in Exercise 1, but now the
program is to write "cold" when the guess is 3 or more away from the correct answer, "warm"
when the guess is 2 away, and "hot" when the guess is 1 away. As soon as the user enters the
correct number the program writes a winning message and exits. For example:
C:>java GuessingGame
I am thinking of a number from 1 to 10.
You must guess what it is in three tries.
Enter a guess:
1
cold
5
RIGHT!
You have won the game.
C:>java GuessingGame
I am thinking of a number from 1 to 10.
You must guess what it is in three tries.
Enter a guess:
4
cold
5
cold
8
wrong.
The correct number was 9.
You have lost the game.
C:>java GuessingGame
I am thinking of a number from 1 to 10.
You must guess what it is in three tries.
Enter a guess:
4
hot
5
warm
3
RIGHT!
You have won the game.
Exercise 3 — Further Improved Guessing Game
Write an even more complicated guessing game. In this version, the full game consists of 10
"rounds," where each round is a game like exercise 2. After the 10 rounds, the program prints
out how many of the 10 rounds were won and how many were lost.
 players who win 7 or fewer rounds are rated as "amateurs,"
Prepared by R. Arthy, AP/IT 35
 players who win 8 rounds are rated as "advanced,"
 players who win 9 rounds are rated as "professionals," and
 players who win all 10 rounds are rated as "hackers."
Here is an example run:
C:>java GuessingGame
round 1:
I am thinking of a number from 1 to 10.
You must guess what it is in three tries.
Enter a guess:
4
hot
5
RIGHT!
You have won 1 out of 1 rounds.
round 2:
I am thinking of a number from 1 to 10.
You must guess what it is in three tries.
Enter a guess:
10
cold
5
cold
3
wrong
The correct number was 1
You have won 1 out of 2 rounds.
. . .
round 10:
I am thinking of a number from 1 to 10.
You must guess what it is in three tries.
Enter a guess:
1
cold
6
warm
8
RIGHT!
You have won 7 out of 10 rounds.
Your rating: amateur.
Prepared by R. Arthy, AP/IT 36
C:>
Exercise 4 — Password Generator
This exercise is based on the PasswordGenerator program in the chapter.
To improve the password, edit the string of characters choices so that it contains more
digits, increasing the chances that digits will be picked. Do this by appending "1234567890"
several more times on to the end of choices. There is no need for choices to contain
only one of each character. If you want punctuation your passwords, append those characters
to the string, as well.
Another improvement is to require that a password have at least one digit. There are several
ways in which this can be done. Don't assume that the required digit in a password will be in
a fixed location.
A further improvement is the rule that every consonant must be followed by a vowel of the
same case. This will make passwords easier to memorize. Of course, it also makes them
easier to guess, especially if a cracker knows that this rule is being used.
Exercise 5 — Password Cracker
A password generator can also be used as a password cracker. Essentially, the generator keeps
creating passwords until it finds one that works. (It is for this reason that most applications
reject a logon attempt if the password fails three times.)
Write a program that asks the user for a password. The user enters a password (which must be
short). Now pretend that this password is a secret from the rest of the program, which must
try to guess it. The program then uses the password generator repeatedly until a randomly
generated password matches the password the user entered. Assume that the user's password
is five characters or less (otherwise the program will run for eons). Write out the number
attempts it took to find the password. Here are some example runs:
K:cai>java PasswordCracker
Enter a "secret" password-->ant
Here is your password: ant
It took 2181892 tries to guess it
K:cai>java PasswordCracker
Enter a "secret" password-->rats
Here is your password: rats
It took 10956100 tries to guess it
K:cai>java PasswordCracker
Enter a "secret" password-->frog
Here is your password: frog
It took 91555945 tries to guess it
K:cai>java PasswordCracker
Enter a "secret" password-->moose
Here is your password: moose
It took 279530402 tries to guess it
Prepared by R. Arthy, AP/IT 37
A better cracker program would systematically generate all possible one-letter passwords,
then all possible two-letter passwords, then all possible three-letter passwords,..., and so on,
comparing each one to the secret password. This program is hard to write without arrays (a
subject of a future chapter).
Exercise 6 — 1D Random Walk
A one dimensional random walk is where a particle starts out at X=0.0, then moves right or
left along the X axis by random amounts. Note that X can be negative or positive (or zero).
Think of it as a bead an a string, randomly being shaken back and forth.
Write a program that initializes to zero a variable X, representing the position of the bead,
then repeatedly adds random amounts in the range (-1.0, +1.0) to X. The program stops after a
specified number of iterations. You will need to use the nextDouble() method of
Random and transform it to match the specified range.
How distant from its starting position is X after 100 iterations? 1000? What is the maximum
distance it coule be? How likely is that?
K:cai>java RandomWalkOneDim
How many iterations?
100
After 100 moves X is now at 1.1190381131949723
K:cai>java RandomWalkOneDim
How many iterations?
1000
After 1000 moves X is now at -0.4633309201402265
Change the program so that it keeps iterating until the bead reaches a particular distance
(positive or negative) from the origin. Use Math.abs() to determine the distance. If you
pick a large distance, you may have to kill the running program, since the distance may never
be reached. (On Windows systems, do this with control-D in the DOS window.)
Exercise 7 — 2D Random Walk
A two dimensional random walk is where a particle starts out at X=0.0, Y=0.0 then moves by
small random increments in both X and Y. Think of it as a confused ant, randomly walking on
the 2D plane.
Write a program that initializes to zero two variables X and Y, representing the position of the
ant, then repeatedly adds random amounts in the range (-1.0, +1.0) to each of them. Pick two
random amounts, one for X and one for Y. The program stops after a specified number of
iterations and prints out the values of the coordinates and the final distance of the ant from
the origin. Use the Pythagorean formula to calculate the distance:
_______
distance = /X2
+ Y2
There are plenty of variations on this program, for instance, counting the iterations it takes to
reach a certain distance. Or, implement two ants, each with its own coordinates, which both
Prepared by R. Arthy, AP/IT 38
start out at (0, 0) and wander for 1000 steps. How far apart are the ants? If one ant does not
move, will they be closer or further apart than when they both move?
Of course, another variation is to implement a 3D random walk, with independent variables
X, Y, and Z. Think of this as a confused firefly, fluttering randomly through the night.
Exercise 8 — Square Root Game
Write a program that implements a two player game. The computer is the score keeper and
the two players are humans. Each round of the game starts with the computer randomly
picking a double precision number from 1.0 to slightly less than 100.0. Each player estimates
the square root of the number and enters the estimate. The player who's estimate is closest to
correct wins the round. Players alternate who goes first in each round. Play ends after a
specified number of rounds.
How many rounds? 4
First Player, sign in--> Dweezle
Secnd Player, sign in--> Moon Unit
What is the square root of 83.29097831183603 ?
Dweezle, your guess: 9.1
Moon Unit, your guess: 9.2
The correct square root: 9.126389116832353
Dweezle is 0.026389116832353565 away
Moon Unit is 0.07361088316764608 away
Dweezle wins!
What is the square root of 87.79346957866132 ?
Moon Unit, your guess: 8.8
Dweezle, your guess: 8.9
The correct square root: 9.36981694477866
Dweezle is 0.46981694477866043 away
Moon Unit is 0.5698169447786601 away
Dweezle wins!
What is the square root of 67.44682032701256 ?
Dweezle, your guess: 8.2
Moon Unit, your guess: 8.1
The correct square root: 8.212601313044033
Dweezle is 0.012601313044033446 away
Moon Unit is 0.11260131304403309 away
Dweezle wins!
What is the square root of 71.64725527288849 ?
Moon Unit, your guess: 8.4
Dweezle, your guess: 8.45
The correct square root: 8.464470170831042
Dweezle is 0.01447017083104285 away
Moon Unit is 0.06447017083104178 away
Dweezle wins!
Prepared by R. Arthy, AP/IT 39
---- Final Score ----
Dweezle: 4 Moon Unit: 0
Call Scanner.nextLine() to read in the end of line characters after the number of
iterations. Then read in the player names using Scanner.nextLine(). Use
nextDouble() for the estimates. Math.abs() and Math.sqrt() will be useful.
Exercise 9 — Pig-like Dice Game
This is a dice game similar to the game Pig, but easier to implement. The player plays against
the computer.
1. Player and Computer start out with zero points.
2. The winner is the first player to reach 100 points or more.
3. In each round, the computer rolls first, followed by the player.
4. The computer rolls three dice and the sum of spots is added to its score.
5. At the start of the player's turn, a working sum is initialized to zero.
6. The player then rolls a single die as many times as desired.
o If the die shows a 1 (on the first roll or any roll), then the player's turn is over
and nothing is added to the player's score.
o For rolls other than 1, the roll is added to the working sum.
o If the player stops rolling before a 1 occurs, then the working sum is added to
the player's score.
In a genuine Pig game, the computer would repeatedly throw a single die (just like the player)
and use strategy to determine when to stop.
Files
Exercise 1 — Control Characters
Write a program that writes ten x's to the screen (modify the HelloWorld.java program). Use
file redirection to send the program's output to a text file. Use the DIR command (or in Unix,
the ls -l command) to see how many bytes are in the file. Depending on how your
operating system implements end of lines, you will see more than 10 bytes.
C:>java Hello > output.txt
C:>dir output.txt
08/13/99 07:01p 12 output.txt
1 File(s) 12 bytes
392,968,704 bytes free
Prepared by R. Arthy, AP/IT 40
The additional two bytes are the control characters that indicate the end of the line. On a
Windows system these control characters are carriage return followed by line feed.
Exercise 2 — More Control Characters
Modify the program so that it outputs 10 lines of 10 x's. Run it, redirect the output to a file,
and examine the file. (It would be a very good idea to be sure that you don't have an infinite
loop before you redirect the output to a file.)
C:>java Hello > output.txt
C:>dir output.txt
08/13/99 07:05p 120 output.txt
1 File(s) 120 bytes
392,968,704 bytes free
The previous file has been replaced by a new file (with the same name).
Exercise 3 — Appending to an Existing File
Now run the original program 10 times in a row. In the first run create a new text file. With
each additional run append the output to the first file. Check if the length is the same as in
Exercise 2:
C:>java Hello > output.txt
C:>java Hello >> output.txt
. . . . . . . . . . .
C:>java Hello >> output.txt
C:>dir output.txt
08/13/99 07:15p 120 output.txt
1 File(s) 120 bytes
392,968,704 bytes free
The file has the same characters as the previous program that used a loop.
Exercise 4 — Really Small File
Now modify the program so that it outputs no characters. Redirect the output to a file. Is a file
created (even though it contains no data?) What size is it?
Exercise 5 — Text Editor
Write a program that asks the user to enter lines of text. After each line the program echos the
line to the terminal. The program finishes when the user enters a line that contains the
characters //done (use a sentinel-controlled loop and the equals() method of class String.)
Once the program is working, run it, and redirect the output to a file.
Prepared by R. Arthy, AP/IT 41
If everything is working, try using your program to create a small Java source file by running
the small editor and typing in the lines of the new program. You can correct mistakes as long
as you are on the same line, but once you hit "enter" that line is committed. In the following
example, the user creates the file Hello.java using the small editor, and then compiles and
runs it.
D:> java TextEdit > Hello.java
class Hello
{
public static void main( String[] a )
{
System.out.println("Hello new File!");
}
}
//done
D:> javac Hello.java
D:> java Hello
Hello new FIle!
What is going on: As far as Java is concerned, characters read from the terminal with
Scanner.nextLine() are just ordinary characters that can be read into a string. While
you (the user) are entering a line of characters from the keyboard you are interacting with the
operating system. It is the operating system that allows you to edit a line with backspace,
delete, and other characters. Once you hit enter, the OS sends the characters to Scanner.
Note: this is a short program, about 15 lines, counting everything. If your program is getting
to be longer than that, you are somehow making it more complicated than it needs to be.
Exercise 1 — Sum of a file of Integers
Write a program that adds all the integers in a file of text integers. This program will be
similar to the ManySquares example program of the chapter and will use a similar input
file. Prompt the user for the name of the input file.
Exercise 2 — Average and Standard Deviation of a file of Doubles
Write a program that computes the average and standard deviation of the text floating point
numbers in a file. Use the following formulas for the average and the standard deviation of N
values. The formulas compute the sum, the sum of squares, the average, the average square,
the variance, and finally, the standard deviation.
sum = x1 + x2 + x3 + ... + xN-1 + xN
sumSQ = x1
2
+ x2
2
+ x3
2
+ ... + xN-1
2
+ xN
2
avg = sum/N
avgSQ = avgSQ/N
Prepared by R. Arthy, AP/IT 42
var = avgSQ - avg2
sd = var(1/2)
The input file will contain any number text floating point numbers, similar to the following:
10.5
12.9
9.67
12.05
8.23
10.08
10.23
7.7
10.4
11.34
Numbers could be several, or none per line, and negative numbers are perfectly OK. For
debugging purposes, use a file that contains one hundred values of 10.0. (You can easily
make such a file using copy and paste with your text editor.) The average should be 10.0 and
the standard deviation should be 0.0.
Now try a file that contains fifty values 10.0 and fifty values -10.0. The average should be 0.0
and the standard deviation should be 10.0.
Exercise 3 — Number Filter
Write a program that reads integers from a text file. The program writes out the positive
integers in the input file to one output file and the negative integers to a second output file.
Prompt the user for the names of all three files.
Exercise 4 — Separate Sums
Say that a text file looks like this:
x= 10
y= -45
y= 98
x= 13
x= 37
y= 36
x= -2
. . .
Each line starts with "x=" or "y=" but which of these it starts with follows no pattern. Each of
these is followed by a space then a single integer. Nothing else follows the integer on a line.
Write a program that reads in this data file and computes the sum of the x values and the sum
of the y values. Hint: use hasNext() and next() to read the "x=" and "y=" tokens and
then use nextInt() to read the integer. You will also need the equals() method of
String.
Prepared by R. Arthy, AP/IT 43
Exercise 5 — Stop Word Remover
Write a program that reads in a file of text, perhaps the text of a novel. The program copies
the same text to an output file, except that all the useless words such as "the", "a", and "an"
are removed. (Decide on what other words you with to remove. The list of words removed is
called a stop list.) Do this by reading the text file token by token using hasNext() and
next(), but only writing out tokens not on the stop list.
Prompt the user for the names of the input and output files.
Fairly Easy: The output file will have only N tokens per line. Do this by counting tokens as
you output them. N will be something like 10 or 12.
Improved Program: Preserve the line structure of the input file. Do this by reading each line
using nextLine() and then creating a new Scanner for that line. (Look at the on-line
documentation for Scanner.) With each line's Scanner, use hasNext() and next() to
scan through its tokens.
Harder: Write out no more than N characters per line. N will be something like 50. Do this
by keeping count of the number of characters written out per line. The length() method of
String will be useful. If X characters has already been written to the current line, and if X
plus the length of the current token exceeds N, then start a new line.
Exercise 6 — E-Mail Address Extractor
write a program that scans a text file for possible e-mail addresses. Addresses look like this:
someone@somewhere.net
Read tokens from the input file one by one using hasNext() and next(). With the
default delimiters of Scanner, an entire e-mail address will be returned as one token.
Examine each token using the indexOf() method of String. If a token contains an at
sign @ followed some characters later by a period, regard it as a possible e-mail address and
write it to the output file.
Programs such as this scan through web pages looking for e-mail addresses that become the
targets of spam. Because of this, many web pages contain disguised e-mail addresses that
can't easily be automatically extracted
1. Hard: Write a program that reads a text file that contains groups of integers that start with
the word "next". For each group, the program computes and writes out the sum of integers in
that group. There may be any number of groups. Example data set:
next
12 45
92 -12 31
next
42 51 275 82 -274
-1 0 26 365
-56
72
next
90 93 91 95
Prepared by R. Arthy, AP/IT 44
97 96 98
For this data the program writes:
Sum of group 1 is 168
Sum of group 2 is 582
Sum of group 3 is 660
Here is another set of data:
next
1 1 1 1 1 1
next
next
1 1 1 1 1 1 1 1 1
next
10 11
12 13
7 8
9
For this data the program writes:
Sum of group 1 is 6
Group 2 contains no data
Sum of group 3 is 9
Sum of group 4 is 70
The logic of this program is quite tricky.
2. Long: Write a program that computes the average change of a value for each of several
groups of data. Input is from a file of data.
Size: about 80 lines, including blank lines and comments
Time to Complete: part of an afternoon
Problem: Say that your are conducting an experiment to determine the effect of a high fiber
diet on cholesterol levels in humans. You have several groups of human subjects. At the
beginning of the experiment the cholesterol level of each subject in each group is measured.
Now the experiment runs for one month. Each group consumes a different amount of fiber
each day. At the end of the month you want to see the change in each group's cholesterol
level.
The data for the experiment is in a text file like the following. Each line of the file contains a
single integer (in character form).
number of groups
number of subjects in group 1
group1 subject1 starting cholesterol
group1 subject1 ending cholesterol
group1 subject2 starting cholesterol
group1 subject2 ending cholesterol
. . . . .
group1 last subject starting cholesterol
Prepared by R. Arthy, AP/IT 45
group1 last subject ending cholesterol
number of subjects in group 2
group2 subject1 starting cholesterol
group2 subject1 ending cholesterol
. . . . .
group2 last subject starting cholesterol
group2 last subject ending cholesterol
number of subjects in group 3
group3 subject1 starting cholesterol
group3 subject1 ending cholesterol
. . . . .
group3 last subject starting cholesterol
group3 last subject ending cholesterol
. . . .
number of subjects in the last group
last group subject1 starting cholesterol
last group subject1 ending cholesterol
last group subject2 starting cholesterol
last group subject2 ending cholesterol
. . . . .
last group last subject starting cholesterol
last group last subject ending cholesterol
For example, the following data file is for three groups. The first group has 2 subjects in it,
the second group has 3 subjects in it, and the last group has 1 subject:
3
2
200
190
212
210
3
240
220
204
208
256
230
1
202
185
Assume that the data is correct (that the counts are correct and all the data is sensible and
comes in complete pairs.) Write the program so that there is any number of groups (including
zero) and so that a group can have any number of subjects in it (including zero.)
You program should do the following: for each group compute and print out the average of
the starting cholesterol values, the average of the ending cholesterol values, and the change in
the averages. For example, with the above data your program should print out something like
this:
Group 1 2 subjects
Prepared by R. Arthy, AP/IT 46
average starting cholesterol: 206
average final cholesterol: 200
change in cholesterol: -6
Group 2 3 subjects
average starting cholesterol: 233
average final cholesterol: 219
change in cholesterol: -14
Group 3 1 subjects
average starting cholesterol: 202
average final cholesterol: 185
change in cholesterol: -17
Done with processing.
Notes: Use integer arithmetic throughout. If a group has zero subjects in it, report that fact
but don't compute the averages (nor print them out.) It would be very helpful for you to plan
this program in advance. The main organization of the program will be a counting loop inside
of a counting loop.
Use some well though out comments in your program to show how it is organized. Be sure
that your indenting also shows how the program is organized.
Here is another sample input file and its output:
4
5
230
210
230
215
230
220
230
225
230
230
3
210
200
210
200
210
200
0
2
200
190
210
200
Group 1 5 subjects
average starting cholesterol: 230
average final cholesterol: 220
change in cholesterol: -10
Prepared by R. Arthy, AP/IT 47
Group 2 3 subjects
average starting cholesterol: 210
average final cholesterol: 200
change in cholesterol: -10
Group 3 0 subjects
Group 4 2 subjects
average starting cholesterol: 205
average final cholesterol: 195
change in cholesterol: -10
Done with processing.
3. Write a program that writes out a table of sines for angles -90.0 to 90.0 in increments of
15 degrees. Use one digit in the decimal fraction for the angle and 6 digits in the decimal
fraction for the sine. Align the decimal points in both columns of numbers.
angle sine
----- --------
-90.0 -1.0
-75.0 -0.965926
-60.0 -0.866025
-45.0 -0.707107
-30.0 -0.5
-15.0 -0.258819
0.0 0.0
15.0 0.258819
30.0 0.5
45.0 0.707107
60.0 0.866025
75.0 0.965926
90.0 1.0
To align its decimal point, treat zero degrees as a special case.
4. Write a program that calculates the value of a deposit for a given initial deposit, interest
rate, times interest is calculated per year, and number of years. Use the formula:
V = P(1 + r/n)nt
V -- value
P -- initial deposit
r -- interest rate as fraction (eg 0.05)
n -- number of times per year interest is calculated
t -- number of years
Prompt the user for P, r, n, and t. Write out the answer accurate to cents. Put a currency sign
in front of the answer.
Initial deposit: 100
Interest rate : 0.04
Times per year : 4
Number of years: 18
Value: $204.71
Make all variables doubles. Use the method Math.pow( double a, double b) from
java.lang.Math which raises a to the power b.
Prepared by R. Arthy, AP/IT 48
5. Write a program that calculates how many years it takes to double an amount of money
for a given annual interest rate. Use the "Rule of 72" for this: divide 72.0 by the interest rate
to get the approximate number of years it takes to double your money. For example, with
10% interest it takes about 7.2 years.
Prompt the user for the interest rate, and write out the number of years, accurate to tenths.
You might want to confirm the accuracy of this rule by using the previous program

More Related Content

What's hot

Training report of C language
Training report of C languageTraining report of C language
Training report of C languageShashank Kapoor
 
Presentation on battery
Presentation on batteryPresentation on battery
Presentation on batterySheikh Aves
 
System Programming- Unit I
System Programming- Unit ISystem Programming- Unit I
System Programming- Unit ISaranya1702
 
Wireless charging of mobile phones
Wireless charging of mobile phones Wireless charging of mobile phones
Wireless charging of mobile phones Divya Gupta
 
Batteries And Its Maintenance
Batteries And Its MaintenanceBatteries And Its Maintenance
Batteries And Its MaintenanceKumaranGovindan
 
Wireless power transfer seminar ppt
Wireless power transfer seminar ppt  Wireless power transfer seminar ppt
Wireless power transfer seminar ppt Niharikamysoreramaku
 
lead acid battery
lead acid batterylead acid battery
lead acid battery2461998
 
Java Presentation
Java PresentationJava Presentation
Java Presentationpm2214
 
Wireless power transmission ppt
Wireless power transmission pptWireless power transmission ppt
Wireless power transmission pptAishwary Verma
 
Wireless charging of ev's
Wireless charging of ev'sWireless charging of ev's
Wireless charging of ev'sRajatAgrawal110
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesString Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesPrabu U
 
Aircraft Anti collision system using ZIGBEE Communication
Aircraft Anti collision system using ZIGBEE CommunicationAircraft Anti collision system using ZIGBEE Communication
Aircraft Anti collision system using ZIGBEE CommunicationPavanKalyan314
 

What's hot (20)

Training report of C language
Training report of C languageTraining report of C language
Training report of C language
 
Hangman game is interesting
Hangman game is interesting Hangman game is interesting
Hangman game is interesting
 
Presentation on battery
Presentation on batteryPresentation on battery
Presentation on battery
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
JDBC
JDBCJDBC
JDBC
 
Java basic
Java basicJava basic
Java basic
 
Single Pass Assembler
Single Pass AssemblerSingle Pass Assembler
Single Pass Assembler
 
System Programming- Unit I
System Programming- Unit ISystem Programming- Unit I
System Programming- Unit I
 
Wireless charging of mobile phones
Wireless charging of mobile phones Wireless charging of mobile phones
Wireless charging of mobile phones
 
Batteries And Its Maintenance
Batteries And Its MaintenanceBatteries And Its Maintenance
Batteries And Its Maintenance
 
Wireless power transfer seminar ppt
Wireless power transfer seminar ppt  Wireless power transfer seminar ppt
Wireless power transfer seminar ppt
 
embedded-static-&dynamic
embedded-static-&dynamicembedded-static-&dynamic
embedded-static-&dynamic
 
First pass of assembler
First pass of assemblerFirst pass of assembler
First pass of assembler
 
lead acid battery
lead acid batterylead acid battery
lead acid battery
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
 
Batteries
BatteriesBatteries
Batteries
 
Wireless power transmission ppt
Wireless power transmission pptWireless power transmission ppt
Wireless power transmission ppt
 
Wireless charging of ev's
Wireless charging of ev'sWireless charging of ev's
Wireless charging of ev's
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesString Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and Interfaces
 
Aircraft Anti collision system using ZIGBEE Communication
Aircraft Anti collision system using ZIGBEE CommunicationAircraft Anti collision system using ZIGBEE Communication
Aircraft Anti collision system using ZIGBEE Communication
 

Similar to Java conceptual learning material

Lewis jssap3 e_labman02
Lewis jssap3 e_labman02Lewis jssap3 e_labman02
Lewis jssap3 e_labman02auswhit
 
Ecet 370 Education Organization -- snaptutorial.com
Ecet 370   Education Organization -- snaptutorial.comEcet 370   Education Organization -- snaptutorial.com
Ecet 370 Education Organization -- snaptutorial.comDavisMurphyB81
 
Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make YASHU40
 
ECET 370 Exceptional Education - snaptutorial.com
ECET 370 Exceptional Education - snaptutorial.com ECET 370 Exceptional Education - snaptutorial.com
ECET 370 Exceptional Education - snaptutorial.com donaldzs157
 
Getting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingGetting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingHock Leng PUAH
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console ProgramHock Leng PUAH
 
Python Programming - II. The Basics
Python Programming - II. The BasicsPython Programming - II. The Basics
Python Programming - II. The BasicsRanel Padon
 
Develop a system flowchart and then write a menu-driven C++ program .pdf
Develop a system flowchart and then write a menu-driven C++ program .pdfDevelop a system flowchart and then write a menu-driven C++ program .pdf
Develop a system flowchart and then write a menu-driven C++ program .pdfleventhalbrad49439
 
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxJLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxvrickens
 
BTE 320-498 Summer 2017 Take Home Exam (200 poi.docx
BTE 320-498 Summer 2017 Take Home Exam (200 poi.docxBTE 320-498 Summer 2017 Take Home Exam (200 poi.docx
BTE 320-498 Summer 2017 Take Home Exam (200 poi.docxAASTHA76
 

Similar to Java conceptual learning material (20)

Ecet 370 week 1 lab
Ecet 370 week 1 labEcet 370 week 1 lab
Ecet 370 week 1 lab
 
Lewis jssap3 e_labman02
Lewis jssap3 e_labman02Lewis jssap3 e_labman02
Lewis jssap3 e_labman02
 
Ecet 370 Education Organization -- snaptutorial.com
Ecet 370   Education Organization -- snaptutorial.comEcet 370   Education Organization -- snaptutorial.com
Ecet 370 Education Organization -- snaptutorial.com
 
Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make
 
ECET 370 Exceptional Education - snaptutorial.com
ECET 370 Exceptional Education - snaptutorial.com ECET 370 Exceptional Education - snaptutorial.com
ECET 370 Exceptional Education - snaptutorial.com
 
Getting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingGetting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem Solving
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
 
C++ Lab Maual.pdf
C++ Lab Maual.pdfC++ Lab Maual.pdf
C++ Lab Maual.pdf
 
C++ Lab Maual.pdf
C++ Lab Maual.pdfC++ Lab Maual.pdf
C++ Lab Maual.pdf
 
Java execise
Java execiseJava execise
Java execise
 
Project
ProjectProject
Project
 
Let's us c language (sabeel Bugti)
Let's us c language (sabeel Bugti)Let's us c language (sabeel Bugti)
Let's us c language (sabeel Bugti)
 
Python Programming - II. The Basics
Python Programming - II. The BasicsPython Programming - II. The Basics
Python Programming - II. The Basics
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
 
Create and analyse programs
Create and analyse programsCreate and analyse programs
Create and analyse programs
 
Develop a system flowchart and then write a menu-driven C++ program .pdf
Develop a system flowchart and then write a menu-driven C++ program .pdfDevelop a system flowchart and then write a menu-driven C++ program .pdf
Develop a system flowchart and then write a menu-driven C++ program .pdf
 
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxJLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
 
Maxbox starter
Maxbox starterMaxbox starter
Maxbox starter
 
A01
A01A01
A01
 
BTE 320-498 Summer 2017 Take Home Exam (200 poi.docx
BTE 320-498 Summer 2017 Take Home Exam (200 poi.docxBTE 320-498 Summer 2017 Take Home Exam (200 poi.docx
BTE 320-498 Summer 2017 Take Home Exam (200 poi.docx
 

More from ArthyR3

Unit IV Knowledge and Hybrid Recommendation System.pdf
Unit IV Knowledge and Hybrid Recommendation System.pdfUnit IV Knowledge and Hybrid Recommendation System.pdf
Unit IV Knowledge and Hybrid Recommendation System.pdfArthyR3
 
VIT336 – Recommender System - Unit 3.pdf
VIT336 – Recommender System - Unit 3.pdfVIT336 – Recommender System - Unit 3.pdf
VIT336 – Recommender System - Unit 3.pdfArthyR3
 
OOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfOOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfArthyR3
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfArthyR3
 
MongoDB.pdf
MongoDB.pdfMongoDB.pdf
MongoDB.pdfArthyR3
 
REACTJS.pdf
REACTJS.pdfREACTJS.pdf
REACTJS.pdfArthyR3
 
ANGULARJS.pdf
ANGULARJS.pdfANGULARJS.pdf
ANGULARJS.pdfArthyR3
 
JQUERY.pdf
JQUERY.pdfJQUERY.pdf
JQUERY.pdfArthyR3
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301ArthyR3
 
CNS - Unit v
CNS - Unit vCNS - Unit v
CNS - Unit vArthyR3
 
Cs8792 cns - unit v
Cs8792   cns - unit vCs8792   cns - unit v
Cs8792 cns - unit vArthyR3
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit ivArthyR3
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit ivArthyR3
 
Cs8792 cns - unit i
Cs8792   cns - unit iCs8792   cns - unit i
Cs8792 cns - unit iArthyR3
 
Java quick reference
Java quick referenceJava quick reference
Java quick referenceArthyR3
 
Cs8792 cns - Public key cryptosystem (Unit III)
Cs8792   cns - Public key cryptosystem (Unit III)Cs8792   cns - Public key cryptosystem (Unit III)
Cs8792 cns - Public key cryptosystem (Unit III)ArthyR3
 
Cryptography Workbook
Cryptography WorkbookCryptography Workbook
Cryptography WorkbookArthyR3
 
Cs6701 cryptography and network security
Cs6701 cryptography and network securityCs6701 cryptography and network security
Cs6701 cryptography and network securityArthyR3
 
Compiler question bank
Compiler question bankCompiler question bank
Compiler question bankArthyR3
 

More from ArthyR3 (20)

Unit IV Knowledge and Hybrid Recommendation System.pdf
Unit IV Knowledge and Hybrid Recommendation System.pdfUnit IV Knowledge and Hybrid Recommendation System.pdf
Unit IV Knowledge and Hybrid Recommendation System.pdf
 
VIT336 – Recommender System - Unit 3.pdf
VIT336 – Recommender System - Unit 3.pdfVIT336 – Recommender System - Unit 3.pdf
VIT336 – Recommender System - Unit 3.pdf
 
OOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfOOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdf
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdf
 
MongoDB.pdf
MongoDB.pdfMongoDB.pdf
MongoDB.pdf
 
REACTJS.pdf
REACTJS.pdfREACTJS.pdf
REACTJS.pdf
 
ANGULARJS.pdf
ANGULARJS.pdfANGULARJS.pdf
ANGULARJS.pdf
 
JQUERY.pdf
JQUERY.pdfJQUERY.pdf
JQUERY.pdf
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301
 
CNS - Unit v
CNS - Unit vCNS - Unit v
CNS - Unit v
 
Cs8792 cns - unit v
Cs8792   cns - unit vCs8792   cns - unit v
Cs8792 cns - unit v
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit iv
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit iv
 
Cs8792 cns - unit i
Cs8792   cns - unit iCs8792   cns - unit i
Cs8792 cns - unit i
 
Java quick reference
Java quick referenceJava quick reference
Java quick reference
 
Cs8792 cns - Public key cryptosystem (Unit III)
Cs8792   cns - Public key cryptosystem (Unit III)Cs8792   cns - Public key cryptosystem (Unit III)
Cs8792 cns - Public key cryptosystem (Unit III)
 
Cryptography Workbook
Cryptography WorkbookCryptography Workbook
Cryptography Workbook
 
Cns
CnsCns
Cns
 
Cs6701 cryptography and network security
Cs6701 cryptography and network securityCs6701 cryptography and network security
Cs6701 cryptography and network security
 
Compiler question bank
Compiler question bankCompiler question bank
Compiler question bank
 

Recently uploaded

Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 

Recently uploaded (20)

Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 

Java conceptual learning material

  • 1. Prepared by R. Arthy, AP/IT 1 DEPARTMENT OF INFORMATION TECHNOLOGY CONCEPTUAL LEARNING JAVA COURSE – ASSESSMENT QUESTIONS Prepared by R. ARTHY, AP/IT
  • 2. Prepared by R. Arthy, AP/IT 2 DEPARTMENT OF INFORMATION TECHNOLOGY Conceptual Learning Java Programming Questions Primitive data type Exercise 1 — Shortfall The following program uses primitive data type short: class Shortfall { public static void main ( String[] args ) { short value = 32; System.out.println("A short: " + value); } } value in this program is a variable—a name for a section of memory that holds data using a particular data type. In this case value is the name for 16 bits of main memory that uses short to represent an integer. (The next chapter says much more about variables.) This program puts the value 32 into value. Then it writes out: A short: 32 In other words, that line of the program examines the variable and writes out what it finds. Your Job: Create a file called Shortfall.java that contains this program. (Copy and paste will greatly speed this up.) Compile and run the program. Check what it writes onto the screen. Now edit the program so that the 32 is changed to some other small number, say 356. Compile and run the program. Everything should be fine. Next change the number to 35000 and try to compile and run the program. This number is too large to work with the data type short (in other words, it cannot be represented in 16 bits using data type short.) What happens? Now edit the program (don't change the 35000) so that the data type is int. Compile and run the program. Is there a difference? Exercise 2 — Double Jeopardy The following program uses primitive data type double: class DoubleJeopardy
  • 3. Prepared by R. Arthy, AP/IT 3 { public static void main ( String[] args ) { double value = 32; System.out.println("A double: " + value); } } In this program, value is the name for a variable that uses the double data type to represent floating point numbers. Recall that this data type uses 64 bits. It is perfectly OK to use the name value in this and in the previous program. A variable name helps describe what you want the program to do. It does not permanently reserve part of computer memory for any particular use. Compile and run the program. Does its output (what it puts on the screen) differ from the output of the the previous exercise? Change the 32 to 32.0 and see if that makes a difference when you compile and run the program. Now try to "break" the program. Look back in this chapter at the chart of primitive data types and the range of values they can hold. Change the "32" to a value that is too big for double. You may wish to use scientific notation for this. Exercise 3 — Exponential Explosion The following program also primitive data type double. This program computes and writes out the value of exp( 32 ). This is the number "e" raised to the power 32. ("e" is the base of natural logarithms. Don't worry much about this. The point of the program is not the math but the floating point numbers.) class ExponentialExplosion { public static void main ( String[] args ) { double value = 32; System.out.println("e to the power value: " + Math.exp( value ) ); } } Compile and run the program. Does it compile and run correctly? Now change the 32 to larger and larger numbers until something goes wrong. Exercise 4 — Character Assassination The following program uses primitive data type char: class CharAssassination {
  • 4. Prepared by R. Arthy, AP/IT 4 public static void main ( String[] args ) { char ch = 'A' ; System.out.println("A char: " + ch ); } } The variable ch is 16 bits of main memory that uses the char data type to represent characters. The a bit pattern that represents 'A' is placed in it. The program writes: A char: A Do the following:  Change the 'A' into 'Z' and compile and run.  Change the 'A' into 'AA' and try to compile the program.  Change the 'A' into ' ' and compile and run the program.  Notice carefully: there is a single space between the two ' marks.  Change the 'A' into '' and try to compile.  Notice carefully: there is no character between the two ' marks.  Change the 'A' into "A" and try to compile the program.  (The double quotes " signify a String, which is something different from a char). Observe and explain what works and what does not work in the above. Variable and Assignment Exercise 1 — Payroll Program Examine this program (from the chapter): class Example { public static void main ( String[] args ) { long hoursWorked = 40; double payRate = 10.0, taxRate = 0.10; System.out.println("Hours Worked: " + hoursWorked ); System.out.println("pay Amount : " + (hoursWorked * payRate) ); System.out.println("tax Amount : " + (hoursWorked * payRate * taxRate) ); } } Modify it so that each variable is declared by itself and is not initialized. Next write three assignment statements to assign a value to each variable. Run the program; examine the output.
  • 5. Prepared by R. Arthy, AP/IT 5 Now let's break something: Remove one of the declarations from the program. Can you compile it? Now remove one of the initializations from the correct program. (For example, delete the characters "= 40" from the first declaration. Try to compile and run the program. When is a problem detected? Exercise 2 — Value of a Quadradic Say that you are interested in the value of the quadratic 3X2 -8X + 4 for several values of X. Write a program that has a double precision variable X. Assign a value to it. Write statement that computes a value for the quadradic and stores the result in another double precision variable. Finally write out the result, something like: At X = 4.0 the value is 20.0 Run the program with several values for X (edit the program for each value of X) and examine the result. Use values with decimal points, large values, small values, negative values, and zero. Solve the equation with paper and pencil (use the quadradic formula.) The quadradic should evaluate to zero at X = 2.0 and at X = 2/3. Try these values for X. Are the results exactly correct? Exercise 3 — Reassigning values to Variables Modify the program in exercise 2 so that one run of the program will evaluate and write out the value of the quadradic for three different values of X: 0.0, 2.0, and 4.0 (or any three values of your choice.) Write the program using only two variables, probably called x and value. Of course this means that you will have to put different things in these variables in different places in the program. In writing the program make use of your editor's "copy" and "paste" functions to avoid re- typing similar lines. Expressions and Arithmetic Operator Exercise 1 — Average Rain Fall Write a program that averages the rain fall for three months, April, May, and June. Declare and initialize a variable to the rain fall for each month. Compute the average, and write out the results, something like: Rainfall for April: 12 Rainfall for May : 14 Rainfall for June: 8 Average rainfall: 11.333333
  • 6. Prepared by R. Arthy, AP/IT 6 To get the numerical values to line up use the tabulation character 't' as part of the character string in the output statements. Check that your program prints the correct results. There is a beginner's error lurking in this program too! Did you fall victim to it? Exercise 2 — Trigonometry To compute the sine of a double precision value use this method: Math.sin( value ) The value is in radians (not degrees.) The cosine is computed using Math.cos( value ) Again, value is in radians. Write a program that: 1. Computes the sine of 0.5236 radians and saves it in a variable. 2. Computes the cosine of 0.5236 radians and saves it in another variable. 3. Computes the square of each those two values (use the variables), adds the two squares, and saves the result (in a third variable.) 4. Writes out the three variables. The output statement should be something like: System.out.println("sine: " + sinx + " cosine: " + cosx + " sum: " + sum ); Try a few other values besides 0.5236. Exercise 3 — Degrees to Radians It is sometimes hard to think in terms of radians; we would rather use degrees. Remember (from those dark days of trigonometry class) that there are PI radians per 180 degrees. So to convert an angle given in degrees to radians do this: rad = degrees * Math.PI/180 Math.PI gives you an accurate value of PI. Edit the previous program so that it does the same things, but the angle is 30 degrees (which you will convert into radians.) Object Exercise 1 — Object Created at Run Time Write a program that creates a String object that contains the string "Hello World" (or some other favorite string). Assign the reference to the object to the reference variable str. Write the characters of the object to the monitor:
  • 7. Prepared by R. Arthy, AP/IT 7 System.out.println( str ); Run the program to confirm that it works as you expect. Now add a second reference variable to the program, but don't create an object for it to refer to. Add a statement that uses the second variable as if it held a valid object reference. Run the program, and see what happens: System.out.println( secondVariable ); Play around with this program for a while to cement the notion in you head that an object and its reference variable are different things, and that an object is created at run time. Exercise 2 — String Length Compile and run the StringDemo2 program from the chapter. class StringDemo2 { public static void main ( String[] args ) { String str; int len; str = new String( "Elementary, my dear Watson!" ); len = str.length(); System.out.println("The length is: " + len ); } } Now change the String in various ways and observe the effect on the computed string length. Add extra spaces on either side and in the middle of the string; add more punctuation; insert a tab character (a real tab character, not just spaces). Note that the length of the string "MMMMMM" is the same as "iiiiii". The length is the number of characters, not the actual length of line it takes to print them. Exercise 3 — A String Method that creates a new String It is often useful to trim off extra spaces from both sides of a String. The trim() method of String objects does that. It creates a new String object from an existing one, where the new String object has all the characters of the original except that spaces and tabs have been trimmed off the sides. The original String is not changed. For example, after the following statements have executed String first = new String(" In a Hole in the ground there lived a Hobbit. ") String second; second = first.trim();
  • 8. Prepared by R. Arthy, AP/IT 8 there will be a second object, referred to by second, containing the characters "In a Hole in the ground there lived a Hobbit." Notice that internal extra spaces remain. Write a program (or modify the previous one) that creates a String by calling the trim() of an original String. Write both Strings to the monitor. Experiment with spaces and tabs to determine exactly what is trimmed from the original. Exercise 4 — Play with substring() Compile and run the program from the chapter (repeated below) to confirm it works as described. Then change the 8 to some other value and check if the result is what you expect. class StringDemo3 { public static void main ( String[] args ) { String str = new String( "Golf is a good walk spoiled." ); // create the original object String sub = str.substring(8); //create a new object from the original System.out.println( sub ); } } String objects have another version of the substring() method that looks like this: substring( int beginIndex, int endIndex ) This method creates a new String object based on the original object, but containing only the characters that start at beginIndex and end at endIndex-1. It creates a completely new object; the characters it contains are copies of those in the original object. For example, look at the following: String str = new String( "Golf is a good walk spoiled." ); // create the original object String sub = str.substring(8, 19); //create a new object from the original These create a new object (referenced by sub) containing the characters "a good walk" . Modify your program so that it calls this two-parameter substring(). Experiment with the two parameters to see how they work. Try the following: 1. Make both parameters the same value. 2. Make the first parameter 0, and the last parameter the index of the last character plus one (28 for the example).
  • 9. Prepared by R. Arthy, AP/IT 9 3. Instead of using a literal 28 in the above, use str.length() which will have the value 28. 4. Change the second parameter to 29 in the above. 5. Make the first parameter negative. 6. Reverse the order of the parameters. Both parameters must be in the range 0 .. str.length() and the first must be less than or equal to the second. Good methods that deal sensibly with all possible input values, even those that make no sense. For good security, programmers must expect that some users will maliciously try to find parameters that cause problems or cause odd behavior that can somehow be exploited. Input and Output Exercise 1 — Area of a Circle Write a program that calculates the area of a circle from its radius. The radius will be an integer read in from the keyboard. The user dialog will look like this: D:usersdefault>java CircleArea Input the radius: 3 The radius is: 3 The area is: 28.274333882308138 You will need to use the constant PI which you get by using Math.PI. Exercise 2 — Cents to Dollars Write a program that reads in a number of cents. The program will write out the number of dollars and cents, like this: D:usersdefault>java Dollars Input the cents: 324 That is 3 dollars and 24 cents. (Use integer arithmetic and avoid floating point arithmetic. Review the integer remainder operator % if you are unsure how to proceed.) Exercise 3 — Correct Change When cashiers make change they first try to "fit" dollars into the amount you get back, then try to fit quarters (25 cent coins) into what is left over, they try to fit dimes (10 cent coins) into what is now left over, then try to fit nickels (5 cent coins) into what is left, and finally are left with a few odd cents. For example, say that your change is 163 cents:  One dollar fits into 163, leaving 63 cents.  Two quarters fit into 63 cents, leaving 13 cents.  One dime fits into 13 cents, leaving 3 cents.  No nickels are needed.  Three cents are left.
  • 10. Prepared by R. Arthy, AP/IT 10 Your change is : 1 dollar, two quarters, one dime, and three cents. Write a program that reads how much change is due (in cents) and writes out that amount as dollars, quarters, dimes, nickels, and pennies. Use integers for all variables and all arithmetic. If you are stuck, do an example problem with paper and pencil. Exercise 4 — Ohm's Law Ohm's law relates the resistance of a electrical device (like a heater) to the electric current flowing through the device and the voltage applied to it. The law is: I = V/R Here, V is the voltage (measured in volts), I is the current (measured in amps), and R is the resistance (measured in ohms.) Write a program that asks the user for the voltage and the resistance of a device. The program will then write out the current flowing through it. Use floating point math. Since V and R are integers (converted from user input) you must use a trick to do floating point division. Change the equation to this: I = (V + 0.0)/R The math inside parentheses is done first. So V + 0.0 is done first, and since 0.0 is floating point, so will be the result. Floating Point Exercise 1 Write a program that calculates the annual cost of running an appliance. The program asks the user for the cost per kilowatt-hour and the number of kilowatt-hours the appliance uses in a year: Enter cost per kilowatt-hour in cents 8.42 Enter kilowatt-hours used per year 653 Annual cost: 54.9826 Exercise 2 When a brick is dropped from a tower, it falls faster and faster until it hits the earth. The distance it travels is given by d = (1/2)gt2 Here d is in feet, t is the time in seconds, and g is 32.174. Write a program that asks the user for the number of seconds and then prints out the distance traveled. Enter the number of seconds: 5.4 Distance: 469.096 Use the program to determine how far a brick falls in 100 seconds.
  • 11. Prepared by R. Arthy, AP/IT 11 Exercise 3 The base 2 logarithm of a number is defined by: log2 X = n if 2n = X For example log2 32 = 5, because 25 = 32 log2 1024 = 10, because 210 = 1024 Write a program that inputs a number and outputs its base 2 logarithm. Use floating point input. This problem would be easy, but the Math package does not have a base 2 logarithm method. Instead you have to do this: log2 X = (loge X) / (loge 2) Here, loge X is the natural logarithm of X, which you can compute using Math.log( X ) As usual, X is a double. The user enters floating point numbers: Enter a double: 998.65 Base 2 log of 998.65 is 9.963835330516641 Exercise 4 The harmonic mean of two numbers is given by: H = 2 / ( 1/X + 1/Y ) This is sometimes more useful than the more usual average of two numbers. Write a program that inputs two numbers (as floating point) and writes out both the usual average (the arithmetic mean) and the harmonic mean. Enter X: 12 Enter Y: 16 Arithmetic mean: 14.0 Harmonic mean: 13.714285714285715 IF Statement Exercise 1 — Discount Prices During a sale at a store, a 10% discount is applied to purchases over $10.00. Write a program that asks for the amount of a purchase, then calculates the discounted price. The purchase amount will be input in cents (as an integer): Enter amount of purchases: 2000 Discounted price: 1800
  • 12. Prepared by R. Arthy, AP/IT 12 Use integer arithmetic throughout the program. Exercise 2 — Order Checker Bob's Discount Bolts charges the following prices:  5 cents per bolt  3 cents per nut  1 cent per washer Write a program that asks the user for the number of bolts, nuts, and washers in their purchase and then calculates and prints out the total. As an added feature, the program checks the order. A correct order must have at least as many nuts as bolts and at least twice as many washers as blots, otherwise the order has an error. For an error the program writes out "Check the Order: too few nuts" or "Check the Order: too few washers" as appropriate. Both error messages are written if the order has both errors. If there are no errors the program writes out "Order is OK." In all cases the total price in cents (of the specified number of items) is written out. Number of bolts: 12 Number of nuts: 8 Number of washers: 24 Check the Order: too few nuts Total cost: 108 Use constants for the unit cost of each item. In other words, declare constants such as final int boltPrice = 5;. Exercise 3 — Last Chance Gas Al's Last Chance Gas station sits on Route 190 on the edge of Death Valley. There is no other gas station for 200 miles. Write a program to help drivers decide if they need gas. The program asks for:  The capacity of the gas tank, in gallons.  The indication of the gas gauge in percent (full= 100, three quarters full = 75, and so on).  The miles per gallon of the car. The program then writes out "Get Gas" or "Safe to Proceed" depending on if the car can cross the 200 miles with the gas remaining in the tank. Tank capacity: 12 Gage reading: 50 Miles per gallon: 30
  • 13. Prepared by R. Arthy, AP/IT 13 Get Gas! Use integers for all input and all arithmetic. Exercise 4 — Pie Eating Contest At the State Fair Pie Eating Contest all contestants in the heavyweight division must weigh within 30 pounds of 250 pounds. Write a program that asks for a contestant's weight and then says if the contestant is allowed in the contest. Exercise 5 — Ground Beef Value Calculator Different packages of ground beef have different percentages of fat and different costs per pound. Write a program that asks the user for: 1. The price per pound of package "A" 2. The percent lean in package "A" 3. The price per pound of package "B" 4. The percent lean in package "B" The program then calculates the cost per pound of lean (non-fat) beef for each package and writes out which is the best value. Price per pound package A: 2.89 Percent lean package A: 85 Price per pound package B: 3.49 Percent lean package B: 93 Package A cost per pound of lean:3.4 Package B cost per pound of lean:3.752688 Package A is the best value Assume that the two packages will not come out equal in value. Exercise 5 — Y2K Problem Detector Write a program that asks a user for their birth year encoded as two digits (like "62") and for the current year, also encoded as two digits (like "99"). The program is to correctly write out the users age in years. Year of Birth: 62 Current year: 99 Your age: 37 The program will have to determine when a two digit value such as "62" corresponds to a year in the 20th century ("1962") or the 21st century. Here is another run of the program, where "00" is taken to mean the year 2000: Year of Birth: 62
  • 14. Prepared by R. Arthy, AP/IT 14 Current year: 00 Your age: 38 Assume that ages are not negative. Another run of the program: Year of Birth: 27 Current year: 07 Your age: 80 In the following run, the age of the person could be 6 or 106 depending on the assumptions. Assume that the age will always be less than or equal to 100. Year of Birth: 01 Current year: 07 Your age: 6 Exercise 6 — Wind Chill Index (You will need to include java.Math.* and use floating point input for this exercise.) The wind chill index (WCI) is calculated from the wind speed v in miles per hour and the temperature t in Fahrenheit. Three formulas are used, depending on the wind speed: if (0 <= v <= 4) then WCI = t if (v >=45) then WCI = 1.6t - 55 otherwise, WCI = 91.4 + (91.4 - t)(0.0203v - 0.304(v)1/2 - 0.474) To calculate (v)1/2 use Math.sqrt( double ). Exercise 7 — Your Age in Seconds Write a program that asks for your age in years, months, and days and writes out your age in seconds. Do this by calculating the number of total days you have been alive, then multiply this by the number of hours per day (24), the number of minutes per hour (60), and the number of seconds per minute (60). Assume that there are 365 days per year (ignore leap years). But correctly take account of the different number of days in different months. If the user enters 5 for the number of months, add up the number of days in the first 5 months: 31 + 28 + 31 + 30 + 31 A human lifespan is about 2.5 billion seconds (2.5 billion heart-beats). Exercise 8 — Matinee Movie Tickets Write a program that determines the price of a movie ticket (similar to the one in the chapter). The program asks for the customer's age and for the time on a 24-hour clock (where noon is 1200 and 4:30PM is 1630). The normal adult ticket price is $8.00, however the adult matinee price is $5.00. Adults are those over 13 years. The normal children's ticket price is $4.00, however the children's matinee price is $2.00. Assume that a matinee starts at any time earlier than 5pm (1700). Get the information from the user and then use nested if statements to determine the ticket price. It is usually a good idea to separate the "information gathering phase" (asking the user for age and time) from the "processing phase" of a program (deciding on the ticket price).
  • 15. Prepared by R. Arthy, AP/IT 15 There are many ways in which the if statements can be nested. Sketch out a flowchart as you design your program. Exercise 9 — Midnight Madness Sales of movie tickets has been dropping! In an effort to attract more viewers, the theater has started a new policy charging $4.00 for all tickets sold after 2200 (10PM). However, no children may purchase tickets after that time. Add logic to the program of exercise 8 to implement the new policy. Branch IF Exercise 1 — Internet Delicatessen You have been asked to write a program for the Sam and Ella Delicatessen. The program takes deli orders from the Internet. It asks for the item, its price in cents, and if overnight shipping is wanted. The program writes out the order and the charges. Regular shipping for items under $10 is $2.00; for items $10 or more shipping is $3.00. For overnight delivery add $5.00. Enter the item: Tuna Salad Enter the price: 450 Overnight delivery (0==no, 1==yes): 1 Invoice: Tuna Salad 4.50 shipping 7.00 total 11.50 (Use our console I/O methods. A real Internet order form would use different I/O methods, but ignore this.) Exercise 2 — Steam Engine Efficiency The maximum possible efficiency of a steam engine depends on the temperature of the steam in the boiler and the temperature of the outside air: efficiency = 1 - Tair / Tsteam where Tair is the air temperature and Tsteam is the steam temperature. The temperatures are give in degrees above absolute zero. Normal air temperature is about 300o K. Boiling is 373o K. Write a program that asks the user for the air temperature and the steam temperature and writes out the maximum possible efficiency of a steam engine. However, if the steam temperature is less than 373o K there is no steam, so the efficiency is zero. Use integer or floating point input, but do the calculations in floating point. Exercise 3 — Microwave Oven A microwave oven manufacturer recommends that when heating two items, add 50% to the heating time, and when heating three items double the heating time. Heating more than three items at once is not recommended.
  • 16. Prepared by R. Arthy, AP/IT 16 Write a program that asks the user for the number of items and the single-item heating time. The program then writes out the recommended heating time. Hint: do this with four successive single-branch if statements each of which tests for one of the four cases: 1 item, 2 items, 3 items, more than three items. Look at the sports car purchase program in the chapter to see how to do this, if you are stuck. Exercise 4 — Fantasy Game In a new role-playing fantasy game players must design their character by picking a point value for each of three characteristics:  Strength, from 1 to 10  Health, from 1 to 10  Luck, from 1 to 10 Write a program that asks for a name for the character and asks for the point value of for each of the three characteristics. However, the total points must be less than 15. If the total exceeds 15, then 5 points are assigned to each characteristic Welcome to Yertle's Quest Enter the name of your character: Chortle Enter strength (1-10): 8 Enter health (1-10): 4 Enter luck (1-10): 6 You have give your character too many points! Default values have been assigned: Chortle, strength: 5, health: 5, luck: 5 (This user interface could get much more complicated. You might want to implement some of your own ideas.) Boolean Expression Exercise 1 — Check Charge A bank has the following rule: if a customer has more than $1000 dollars in their checking account or more than $1500 dollars in their savings account, then there is no service charge for writing checks. Otherwise there is a $0.15 charge per check. Write a program that asks for the balance in each account and then writes out the service charge. Exercise 2 — Tire Pressure The front tires of a car should both have the same pressure. Also, the rear tires of a car should both have the same pressure (but not necessarily the same pressure as the front tires.) Write a
  • 17. Prepared by R. Arthy, AP/IT 17 program that reads in the pressure of the four tires and writes a message that says if the inflation is OK or not. Input right front pressure 38 Input left front pressure 38 Input right rear pressure 42 Input left rear pressure 42 Inflation is OK Exercise 3 — More Tire Pressure Its not enough that the pressures are the same in the tires, but the pressures must also be within range. Modify the program in exercise 1 so that it also checks that each tire has a pressure between 35 and 45. If a tire is out of range, write out an error message immediately, but continue inputting values and processing them: Input right front pressure 32 Warning: pressure is out of range Input left front pressure 32 Warning: pressure is out of range Input right rear pressure 42 Input left rear pressure 42 Inflation is BAD If there have been any warnings, write out a final error message. (To do this, declare a boolean variable goodPressure that is initialized to true but is changed to false when an out of range tire is first found.) Exercise 4 — The Pressure is Building Tires don't have to have exactly the same pressure. Modify the program for exercise 2 so that the front tires can be within 3 psi of each other, and the rear tires can be within 3 psi of each other. Input right front pressure 35 Input left front pressure 37 Input right rear pressure 41 Input left rear pressure
  • 18. Prepared by R. Arthy, AP/IT 18 44 Inflation is OK Looping Exercise 1 Write a program that asks the user for a starting value and an ending value and then writes all the integers (inclusive) between those two values. Enter Start: 5 Enter End: 9 5 6 7 8 9 Exercise 2 Write a program that asks the user to enter a word. The program will then repeat word for as many times as it has characters: Enter a word: Hello Hello Hello Hello Hello Hello To do this you will need to use the length() method that counts the number of characters in a string: String inputString; int times; . . . . times = inputString.length()
  • 19. Prepared by R. Arthy, AP/IT 19 Exercise 3 Write a program that asks the user to enter two words. The program then prints out both words on one line. The words will be separated by enought dots so that the total line length is 30: Enter first word: turtle Enter second word 153 turtle....................153 This could be used as part of an index for a book. To print out the dots, use System.out.print(".") inside a loop body. Methods and Messages Exercise 1 — Adding up Integers Write a program that adds up integers that the user enters. First the programs asks how many numbers will be added up. Then the program prompts the user for each number. Finally it prints the sum. How many integers will be added: 5 Enter an integer: 3 Enter an integer: 4 Enter an integer: -4 Enter an integer: -3 Enter an integer: 7 The sum is 7 Be careful not to add the number of integers (in the example, 5) into the sum. Exercise 2 Write a program that computes the following sum: sum = 1.0/1 + 1.0/2 + 1.0/3 + 1.0/4 + 1.0/5 + .... + 1.0/N N is an integer limit that the user enters. Enter N 4 Sum is: 2.08333333333
  • 20. Prepared by R. Arthy, AP/IT 20 Exercise 3 Write a program that computes the standard deviation of a set of floating point numbers that the user enters. First the user says how many numbers N are to follow. Then the program asks for and reads in each floating point number. Finally it writes out the standard deviation. The standard deviation of a set of numbers Xi is: SD = Math.sqrt( avgSquare - avg2 ) Here, avg is the average of the N numbers, and avg2 is its square. avgSquare is the average of Xi * Xi. In other words, this is the average of the squared value of each floating point number. For example, if N = 4, say the numbers were: Xi Xi * Xi 2.0 4.0 3.0 9.0 1.0 1.0 2.0 4.0 sum 8.0 18.0 Now: avg = 8.0/4 = 2.0 avg2 = 4.0 avgSquare = 18.0/4 = 4.5 SD = Math.sqrt( 4.5 - 4.0 ) = Math.sqrt( .5 ) = 0.7071067812 To do this you will need to do several things inside the loop body for each floating point value as it comes in: add it to a sum, square it and add it to a sum of squares. Then after the loop is finished apply the formula. Inheritance Exercise 1 — Jet Lag Calculator How many days of rest do you need to recover from jet lag? The International Civil Avaiation Organization has a fomula for this: 1. Hours = number of hours of travel 2. Zones = number of time zones crossed 3. Depart = o 0, for departures between 8AM and noon o 1, for departures between noon and 6PM o 3, for departures between 6PM and 10PM
  • 21. Prepared by R. Arthy, AP/IT 21 o 4, for departures between 10PM and 1AM o 5, for departures between 1AM and 8AM 4. Arrive = o 4, for arrivals between 8AM and noon o 2, for arrivals between noon and 6PM o 0, for arrivals between 6PM and 10PM o 1, for arrivals between 10PM and 1AM o 3, for arrivals between 1AM and 8AM The number of days you need to recover is: days of recovery = (Hours/2 + (Zones-3) + Depart + Arrive)/10 For example, say that you are flying from New York Kennedy Airport to London Heathrow. Your flight leaves at 7AM (New York time) and arrives at 7PM (London time). 1. Hours = 7 (London time is New York time + 5) 2. Zones = 4 3. Depart = 5 4. Arrive = 0 days of recovery = (7/2 + (4-3) + 5 + 0)/10 = (3.5 + 1 + 5 + 0)/10 = 9.5/10 = 0.95 days Write a program that asks the user for the number of hours of travel, the number of time zones crossed, the departure time, and the arrival time and then calculates the number of days needed for recovery. Let the user enter time using a 24 hour clock (so 6PM is 18). (Formula from Darrell Huff, How to Figure It, Norton, 1996. Exercise 2 — Adding up Squares and Cubes Write a program that adds up the squares and adds up the cubes of integers from 1 to N, where N is entered by the user: Upper Limit: 5 The sum of Squares is 55 The sum of Cubes is 225 Do this by using just one loop that generates the integers. Of course, if you really needed to calculate these sums you would use the appropriate formulas: 12 + 22 + 32 + ... + n2 = n(n+1)(2n+1)/6 13 + 23 + 33 + ... + n3 = n2 (n+1)2 /4 Add these formulas to your program and print out their results as well as that of the explicit summations.
  • 22. Prepared by R. Arthy, AP/IT 22 Exercise 3 — Power of a number Write a program that computes XN where X is a floating point number and N is a positive integer. The program informs the user that N must be positive if the user enters a negative value. Of course, XN = X * X * X * ... * X <-- N of these The user dialog will look something like this: Enter X 1.3 Enter N 5 1.3 raised to the power 5 is: 3.71293 ------- Enter X 5.6 Enter N -3 N must be a positive integer. Exercise 4 — Wedge of Stars Write a program that writes a wedge of stars. The user enters the initial number of stars, and the program writes out lines of stars. Each line has one few star than the previous line: Initial number of stars: 7 ******* ****** ***** **** *** ** * Exercise 5 — Pine Tree Write a program that writes a tree made of stars on the terminal: * *** ***** ******* ********* *********** ************* ***************
  • 23. Prepared by R. Arthy, AP/IT 23 *** *** *** Exercise 5 — Wallpaper Calculator Write a program that calculates how many rolls of wallpaper you need for a room. Assume that the room is a rectangular prism (the usual shape) of specified width, height, and length. Only the walls will be covered with wallpaper. The room may have several openings (windows, doors) which will not be covered. Wallpaper comes in rolls. A single roll of wallpaper is 27 inches wide and 4.5 yards long. Wallpaper is applied to the walls in vertical strips. Ask the user for the dimensions of the room and the number of openings. Then ask for the dimensions of each opening. Calculate and display the number of full rolls of wallpaper needed. A quick approximation is to calculate the area of the room to be covered (the area of the walls minus the area of the openings), then divide that by the area covered by a roll of wallpaper. Round up to the nearest integer number of rolls. A more accurate calculation allows for walls with a width that is not an integer multiple of the standard width of 27 inches. The last strip of wallpaper for a wall may have to be cut from from a standard width strip, wasting the rest of that strip. Exercise 6 — Float Factorial Change the factorial program so that fact is data type double instead of long. Keep the loop control variable N of type long. Try to figure out how much larger N can be with this program. Of course, since data type double is not precise there will be accuracy errors with large N. For some applications (such as number theory or code breaking) this would not be acceptable. To study this problem further, modify the program to calculate N! / (N-1)!. Of course, this should be N. But if you first calculate the factorials, and then divide them, you will only get an approximation to N. Exercise 7 — Permutaions The formula for the number of permutations of N objects taken R at a time without repitition is N!/(N-R)! Modify the original factorial program (that uses data type long) so that it calculates this value. Ask the user for both N and R where both must be zero or positive and R must be less than or equal to N. Write error messages for incorrect values. Of course, it would not be sensible to separately calculate N! and (N-R)! and then to divide. Design your program so that it does the minimum number of multiplications needed.
  • 24. Prepared by R. Arthy, AP/IT 24 Packages Exercise 1 — Adding Integers AddUpNumbers, the program that adds integers from the user could be improved. In some situations it would not be correct to say that the sum of integers is zero when the user, in fact, entered no integers. (For example, teachers sometimes distinguish between an assignment that got zero points and an assignment that was not turned in.) Modify the program so that it writes a message if the first value entered by the user is the sentinal value of zero. Otherwise, the program proceeds as before. Enter first integer (enter 0 to quit): 0 No integers were entered. bye Enter first integer (enter 0 to quit): 3 Enter an integer (or 0 to quit): -3 Enter an integer (or 0 to quit): 0 Sum of the integers: 0 bye Exercise 2 — Miles per Gallon Write a program that calculates miles per gallon for a list of cars. The data for each car consists of initial odometer reading, final odometer reading, and number of gallons of gas. The user signals that there are no more cars by entering a negative initial odometer reading. Miles Per Gallon Program Initial miles: 15000 Final miles: 15250 Gallons 10 Miles per Gallon: 25.0 Initial miles: 107000 Final miles: 107450 Gallons 15 Miles per Gallon: 30.0 Initial miles: -1 bye
  • 25. Prepared by R. Arthy, AP/IT 25 Exercise 3 — In-range Adder Write a program that asks the user for the low and high integer in a range of integers. The program then asks the user for integers to be added up. The program computes two sums:  The sum of integers that are in the range (inclusive),  and the sum of integers that are outside of the range. The user signals the end of input with a 0. In-range Adder Low end of range: 20 High end of range: 50 Enter data: 21 Enter data: 60 Enter data: 49 Enter data: 30 Enter data: 91 Enter data: 0 Sum of in range values: 100 Sum of out of range values: 151 Exercise 4 — Shipping Cost Calculator A mail order company charges $3.00 for handling, free shipping for orders 10 pounds or less, plus $0.25 for each pound over 10. Write a program that repeatedly asks the user for the weight of an order, then writes out the shipping charge. The program stops when a weight of zero or less is entered. Weight of Order: 5 Shipping Cost: $3.00 Weight of Order 20 Shipping Cost: $5.50 Weight of Order 0 bye
  • 26. Prepared by R. Arthy, AP/IT 26 Exercise 5 — Area of Rectangles A computer aided design program expects users to enter the coordinates two corners for each of several of rectangles (see diagram.) The sides of the rectangles are assumed to be parallel to the X and Y axes. The coordinates of each corner is entered as a pair of integers, first the X coordinate and then the Y coordinate. The origin of the coordinate system (0,0) is in the upper left, so Y increases going downward, and X increases to the right. For each rectangle, the program calculates and writes out the height, the width, and the area of the rectangle. The two corners entered for each rectangle must be diagonally opposite (upper left and lower right, or upper right and lower left), but which choice is made for each rectangle is up to the user. The user can enter the corners in any order. Height and width are always positive (the program will have to adjust its calculations so that this is true.) The program ends gracefully when the user enters corners which cannot be those of a rectangle (either the height is zero, the width is zero, or both.) Computer Aided Design Program First corner X coordinate: 100 First corner Y coordinate: 100 Second corner X coordinate: 250 Second corner Y coordinate 200 Width: 150 Height: 100 Area: 15000 First corner X coordinate: 250 First corner Y coordinate: 200 Second corner X coordinate: 100 Second corner Y coordinate
  • 27. Prepared by R. Arthy, AP/IT 27 100 Width: 150 Height: 100 Area: 15000 First corner X coordinate: 100 First corner Y coordinate: 200 Second corner X coordinate: 250 Second corner Y coordinate 100 Width: 150 Height: 100 Area: 15000 First corner X coordinate: 100 First corner Y coordinate: 100 Second corner X coordinate: 100 Second corner Y coordinate 100 Width: 0 Height: 0 Area: 0 finished Exercise 6 — Login Simulator Write a program that simulates the "login" process of a computer. A loop continuously asks the user for their user name and password. Assume that each is a single word. If the user name and password match one of the correct pairs, allow the user to log on (actually: just print a simulated message). A logged-on user has a priority from 1 (low) to 5 (high). Otherwise print a failure message. If the user name is "quit" with a password "exit", exit the loop and print a final message. Use a if else if structure nested inside a while loop to do this. Use the equals() method of String to compare user data with allowed user names and passwords. User names and passwords are case sensitive. "Hard code" the user names and passwords (that it, make them string literals that are part of each if statement. Here are some sample users and passwords:  user name; password; priority  joy; sun; 4  gates; monopoly; 1  jobs; apple; 3  root; secret; 5 Here is a sample run of the program: User Name: gates
  • 28. Prepared by R. Arthy, AP/IT 28 Password : money Logon failed User Name: gates Password : monopoly You have logged on with priority 1 User Name: hacker Password : crack Logon failed User Name: jobs Password : apple You have logged on with priority 3 User Name: quit Password : exit System shutting down. Bye. The if else if structure is really nothing new; it is a way of indenting your program to emphasize that a choice is being made out of a list of options. Here is a code excerpt that does one of four things, depending on whether choice is 0, 1, 2, or 3. The final else handles the situation where choice is out of range: choice = scan.nextInt(); if ( choice==0 ) { // code for choice 0 } else if ( choice==1 ) { // code for choice 1 } else if ( choice==2 ) { // code for choice 2 } else if ( choice==3 ) { // code for choice 3 } else { // error handling } Exception Handling
  • 29. Prepared by R. Arthy, AP/IT 29 Exercise 1 — Modified Million Dollars Modify the DollarsAfterForty program in the chapter so that it asks the user for the interest rate, the initial investment, and the annual contribution. The program prints out the current value of the investment at the end of each year and continues until it reaches or exceeds one million dollars. Exercise 2 — Credit Card Bill Say that you owe the credit card company $1000.00. The company charges you 1.5% per month on the unpaid balance. You have decided to stop using the card and to pay off the debt by making a monthly payment of N dollars a month. Write a program that asks for the monthly payment, then writes out the balance and total payments so far for every succeeding month until the balance is zero or less. Enter the monthly payment: 100 Month: 1 balance: 915.0 total payments: 100.0 Month: 2 balance: 828.725 total payments: 200.0 Month: 3 balance: 741.155875 total payments: 300.0 Month: 4 balance: 652.273213125 total payments: 400.0 Month: 5 balance: 562.057311321875 total payments: 500.0 Month: 6 balance: 470.4881709917031 total payments: 600.0 Month: 7 balance: 377.54549355657866 total payments: 700.0 Month: 8 balance: 283.20867595992735 total payments: 800.0 Month: 9 balance: 187.4568060993263 total payments: 900.0 Month: 10 balance: 90.26865819081618 total payments: 1000.0 Month: 11 balance: -8.377311936321576 total payments: 1100.0 For each month, calculate the interest due on the unpaid balance. Then calculate the new balance by adding the interest and subtracting the payment. Improved Program: Have the program prompt for the beginning balance, the monthly interest, and the payment amount. Also, when the balance falls below the amount of the monthly payment, write out the final payment that will bring the balance to exactly zero. Further Improved Program: The output of the program is somewhat ugly, with the columns not aligned and too many digits printed in the decimal fractions. This can be improved. Place the following lines in the appropriate places in your program. You will need to modify the last line to fit with the rest of your program. import java.text.*; DecimalFormat numform = new DecimalFormat(); System.out.print( "balance: " + numform.format(balance) ); For details about how this works, see Chapter 24. Exercise 3 — Drug Potency A certain drug looses 4% of its effectiveness every month it is in storage. When its effectiveness is below 50% it is considered expired and must be discarded. Write a program that determines how many months the drug can remain in storage. month: 0 effectiveness: 100.0
  • 30. Prepared by R. Arthy, AP/IT 30 month: 1 effectiveness: 96.0 month: 2 effectiveness: 92.16 month: 3 effectiveness: 88.47359999999999 month: 4 effectiveness: 84.93465599999999 month: 5 effectiveness: 81.53726975999999 month: 6 effectiveness: 78.27577896959998 month: 7 effectiveness: 75.14474781081599 month: 8 effectiveness: 72.13895789838334 month: 9 effectiveness: 69.253399582448 month: 10 effectiveness: 66.48326359915008 month: 11 effectiveness: 63.82393305518407 month: 12 effectiveness: 61.27097573297671 month: 13 effectiveness: 58.82013670365764 month: 14 effectiveness: 56.46733123551133 month: 15 effectiveness: 54.20863798609088 month: 16 effectiveness: 52.04029246664724 month: 17 effectiveness: 49.95868076798135 DISCARDED Exercise 4 — ex One of the more amazing facts from calculus is that the following sum gets closer and closer to the value ex the more terms you add in: e x = 1 + x + x 2 /2! + x 3 /3! + x 4 /4! + x 5 /5! + x 6 /6! + . . . . Remember that n! means n factorial, n*(n-1)*(n-2)* ... *1. For example, if x is 2 then e2 = 1 + 2 + 22 /2! + 23 /3! + 24 /4! + 25 /5! . . . . e2 = 1 + 2 + 4/2 + 8/6 + 16/24 + 32/120 + . . . . e2 = 1 + 2 + 2 + 1.3333 + 0.6666 + 0.2666 + . . . . e2 ~ 7.266 More exactly, e2 = 7.38907... Write a program that asks the user to enter x, then calculates ex using a loop to add up successive terms until the current term is less than 1.0E-12. Then write out the value Math.exp(x) to see how your value compares. To do this program sensibly, the loop will add in a term each iteration. sum = sum + term; Look carefully at the first equation for ex . Notice that each term in the series is: x N /N! for some N. This is the same as: x(N-1) /(N-1)! * x/N
  • 31. Prepared by R. Arthy, AP/IT 31 This is the previous term times x/N. So each iteration of the loop merely has to multiply the previous term by x/N and add it to the accumulating sum. Don't let the math scare you away! This is actually a fairly easy program, and is typical of a type of calculation that computers are often used for. Enter x: 2 n:1 term: 2.0 sum: 3.0 n:2 term: 2.0 sum: 5.0 n:3 term: 1.3333333333333333 sum: 6.333333333333333 n:4 term: 0.6666666666666666 sum: 7.0 n:5 term: 0.26666666666666666 sum: 7.266666666666667 n:6 term: 0.08888888888888889 sum: 7.355555555555555 n:7 term: 0.025396825396825397 sum: 7.3809523809523805 n:8 term: 0.006349206349206349 sum: 7.387301587301587 n:9 term: 0.0014109347442680777 sum: 7.3887125220458545 n:10 term: 2.8218694885361555E-4 sum: 7.388994708994708 n:11 term: 5.130671797338464E-5 sum: 7.389046015712681 n:12 term: 8.551119662230774E-6 sum: 7.3890545668323435 n:13 term: 1.3155568711124268E-6 sum: 7.389055882389215 n:14 term: 1.8793669587320383E-7 sum: 7.3890560703259105 n:15 term: 2.5058226116427178E-8 sum: 7.389056095384136 n:16 term: 3.1322782645533972E-9 sum: 7.389056098516415 n:17 term: 3.6850332524157613E-10 sum: 7.389056098884918 n:18 term: 4.094481391573068E-11 sum: 7.389056098925863 n:19 term: 4.309980412182177E-12 sum: 7.3890560989301735 n:20 term: 4.309980412182177E-13 sum: 7.389056098930604 my e^x: 7.389056098930604 real e^x: 7.38905609893065 Exercise 4 — 1/B by Newton's Method Another amazing fact from calculus is that you can calculate 1/B without doing division. (Assume that B is a positive real number.) Say that x is your first guess for the value 1/B. Then your guess can be improved by using the formula: x' = x*(2-B*x) Of course, now that guess can be further improved by using the same formula. This formula is yet another application of Newton's Method. For example, say that B is 4.0. You want to calculate 1/4. Say that your first guess for this value is 0.1 ; then an improved guess is: x' = 0.1 * (2 - 4*0.1) = 0.1 * (2 - .4) = 0.1*(1.6) = 0.16 The next estimate is: x' = 0.16 * (2 - 4*0.16) = 0.16 * (2 - 0.64) = 0.16 * 1.36 = 0.2176 A further improvement is:
  • 32. Prepared by R. Arthy, AP/IT 32 x' = 0.2176 * (2 - 4*0.2176) = 0.2176 * (2 - 0.8704) = 0.2176 * 1.1296 = 0.24580096 Repeat the formula to further improve the guess. Write a program that asks the user for B and then writes out 1/B without using a division. You will need to think of an appropriate ending condition for the loop that calculates 1/B. Unfortunately, the first guess for this method must be between zero and the true value of 1/B. It sounds like you need division to make the first guess, but this can be avoided by always starting with a hard-coded (a constant that is part of the program) very tiny first guess. For very large values of B your first guess might not be tiny enough, because 1/B is so small. Protect your code with an if statement that checks if B is too large for the program to handle. If the first guess is hard-coded, then you know the maximum value for B. Of course, 1/0 is not defined, so test for this, too. Exercise 5 — Hailstone Numbers Write a program that asks the user for a positive integer N and then calculates a new value for N based on whether it is even or odd: if N is even, the new N is N/2. (Use integer division.) if N is odd, the new N is 3*N + 1. Repeat with each new N until you reach the value 1. For example, say the initial value is 12. Then the successive values are: 12 (even, next value is 12/2) 6 (even, next value is 6/2) 3 (odd, next value is 3*3+1) 10 (even, next value is 10/2) 5 (odd, next value is 3*5+1) 16 (even, next value is 16/2) 8 (even, next value is 8/2) 4 (even, next value is 4/2) 2 (even, next value is 2/2) 1 (stop calculation) The sequence of integers is called a hailstone series because the integers increase and decrease, sometimes many times, before eventually reaching 1. (This is supposed to be like hailstones blowing up and down in a storm before reaching the ground.) For all integers that have been tested (up to 1048 ) the series eventually does reach 1. But no one knows for sure if this is true for all integers. Additional Things to Calculate: In addition to calculating and printing out the sequence for a particular initial N, keep track of the length of the sequence and the maximum integer in the sequence and print them out when the sequence reaches its end. A variation on this program is to generate each sequence for initial numbers from 1 to 1000, and to determine the length and starting number of the longest of those sequences. You
  • 33. Prepared by R. Arthy, AP/IT 33 probably don't want to print out each sequence, just keep track of each length and compare it to the current maximum. Hard: Are there any integers from 1 to 1000 that are not in any hailstone sequence other than the one they start? To write a sensible program that determines this, you will need to use an array, which is the subject of chapter 46. You may wish to return to this problem after you have covered that chapter. Note: it is natural to investigate sequences that start with initial numbers in the millions or higher. The terms of these sequences get very large; larger than can be held in an int variable. Use data type long to avoid these problems. That will work for initial values up to at least five billion. Interface Exercise 1 — Guessing Game Write a program that implements a guessing game. This is a "classic" program, frequently assigned in beginning CS classes. The program picks a random number from 1 to 10. Now the user gets three guesses. As soon as the user enters the correct number the program writes a winning message and exits. If the user fails to enter the correct number in three guesses, the program writes a failure message and exits. Use methods of the Random class. Here are two example runs of the program: C:>java GuessingGame I am thinking of a number from 1 to 10. You must guess what it is in three tries. Enter a guess: 4 wrong 8 RIGHT! You have won the game. C:>java GuessingGame I am thinking of a number from 1 to 10. You must guess what it is in three tries. Enter a guess: 1 wrong 5 wrong 9 wrong The correct number was 7. You have lost the game.
  • 34. Prepared by R. Arthy, AP/IT 34 Exercise 2 — Improved Guessing Game Write a more complicated guessing game, similar to the one in Exercise 1, but now the program is to write "cold" when the guess is 3 or more away from the correct answer, "warm" when the guess is 2 away, and "hot" when the guess is 1 away. As soon as the user enters the correct number the program writes a winning message and exits. For example: C:>java GuessingGame I am thinking of a number from 1 to 10. You must guess what it is in three tries. Enter a guess: 1 cold 5 RIGHT! You have won the game. C:>java GuessingGame I am thinking of a number from 1 to 10. You must guess what it is in three tries. Enter a guess: 4 cold 5 cold 8 wrong. The correct number was 9. You have lost the game. C:>java GuessingGame I am thinking of a number from 1 to 10. You must guess what it is in three tries. Enter a guess: 4 hot 5 warm 3 RIGHT! You have won the game. Exercise 3 — Further Improved Guessing Game Write an even more complicated guessing game. In this version, the full game consists of 10 "rounds," where each round is a game like exercise 2. After the 10 rounds, the program prints out how many of the 10 rounds were won and how many were lost.  players who win 7 or fewer rounds are rated as "amateurs,"
  • 35. Prepared by R. Arthy, AP/IT 35  players who win 8 rounds are rated as "advanced,"  players who win 9 rounds are rated as "professionals," and  players who win all 10 rounds are rated as "hackers." Here is an example run: C:>java GuessingGame round 1: I am thinking of a number from 1 to 10. You must guess what it is in three tries. Enter a guess: 4 hot 5 RIGHT! You have won 1 out of 1 rounds. round 2: I am thinking of a number from 1 to 10. You must guess what it is in three tries. Enter a guess: 10 cold 5 cold 3 wrong The correct number was 1 You have won 1 out of 2 rounds. . . . round 10: I am thinking of a number from 1 to 10. You must guess what it is in three tries. Enter a guess: 1 cold 6 warm 8 RIGHT! You have won 7 out of 10 rounds. Your rating: amateur.
  • 36. Prepared by R. Arthy, AP/IT 36 C:> Exercise 4 — Password Generator This exercise is based on the PasswordGenerator program in the chapter. To improve the password, edit the string of characters choices so that it contains more digits, increasing the chances that digits will be picked. Do this by appending "1234567890" several more times on to the end of choices. There is no need for choices to contain only one of each character. If you want punctuation your passwords, append those characters to the string, as well. Another improvement is to require that a password have at least one digit. There are several ways in which this can be done. Don't assume that the required digit in a password will be in a fixed location. A further improvement is the rule that every consonant must be followed by a vowel of the same case. This will make passwords easier to memorize. Of course, it also makes them easier to guess, especially if a cracker knows that this rule is being used. Exercise 5 — Password Cracker A password generator can also be used as a password cracker. Essentially, the generator keeps creating passwords until it finds one that works. (It is for this reason that most applications reject a logon attempt if the password fails three times.) Write a program that asks the user for a password. The user enters a password (which must be short). Now pretend that this password is a secret from the rest of the program, which must try to guess it. The program then uses the password generator repeatedly until a randomly generated password matches the password the user entered. Assume that the user's password is five characters or less (otherwise the program will run for eons). Write out the number attempts it took to find the password. Here are some example runs: K:cai>java PasswordCracker Enter a "secret" password-->ant Here is your password: ant It took 2181892 tries to guess it K:cai>java PasswordCracker Enter a "secret" password-->rats Here is your password: rats It took 10956100 tries to guess it K:cai>java PasswordCracker Enter a "secret" password-->frog Here is your password: frog It took 91555945 tries to guess it K:cai>java PasswordCracker Enter a "secret" password-->moose Here is your password: moose It took 279530402 tries to guess it
  • 37. Prepared by R. Arthy, AP/IT 37 A better cracker program would systematically generate all possible one-letter passwords, then all possible two-letter passwords, then all possible three-letter passwords,..., and so on, comparing each one to the secret password. This program is hard to write without arrays (a subject of a future chapter). Exercise 6 — 1D Random Walk A one dimensional random walk is where a particle starts out at X=0.0, then moves right or left along the X axis by random amounts. Note that X can be negative or positive (or zero). Think of it as a bead an a string, randomly being shaken back and forth. Write a program that initializes to zero a variable X, representing the position of the bead, then repeatedly adds random amounts in the range (-1.0, +1.0) to X. The program stops after a specified number of iterations. You will need to use the nextDouble() method of Random and transform it to match the specified range. How distant from its starting position is X after 100 iterations? 1000? What is the maximum distance it coule be? How likely is that? K:cai>java RandomWalkOneDim How many iterations? 100 After 100 moves X is now at 1.1190381131949723 K:cai>java RandomWalkOneDim How many iterations? 1000 After 1000 moves X is now at -0.4633309201402265 Change the program so that it keeps iterating until the bead reaches a particular distance (positive or negative) from the origin. Use Math.abs() to determine the distance. If you pick a large distance, you may have to kill the running program, since the distance may never be reached. (On Windows systems, do this with control-D in the DOS window.) Exercise 7 — 2D Random Walk A two dimensional random walk is where a particle starts out at X=0.0, Y=0.0 then moves by small random increments in both X and Y. Think of it as a confused ant, randomly walking on the 2D plane. Write a program that initializes to zero two variables X and Y, representing the position of the ant, then repeatedly adds random amounts in the range (-1.0, +1.0) to each of them. Pick two random amounts, one for X and one for Y. The program stops after a specified number of iterations and prints out the values of the coordinates and the final distance of the ant from the origin. Use the Pythagorean formula to calculate the distance: _______ distance = /X2 + Y2 There are plenty of variations on this program, for instance, counting the iterations it takes to reach a certain distance. Or, implement two ants, each with its own coordinates, which both
  • 38. Prepared by R. Arthy, AP/IT 38 start out at (0, 0) and wander for 1000 steps. How far apart are the ants? If one ant does not move, will they be closer or further apart than when they both move? Of course, another variation is to implement a 3D random walk, with independent variables X, Y, and Z. Think of this as a confused firefly, fluttering randomly through the night. Exercise 8 — Square Root Game Write a program that implements a two player game. The computer is the score keeper and the two players are humans. Each round of the game starts with the computer randomly picking a double precision number from 1.0 to slightly less than 100.0. Each player estimates the square root of the number and enters the estimate. The player who's estimate is closest to correct wins the round. Players alternate who goes first in each round. Play ends after a specified number of rounds. How many rounds? 4 First Player, sign in--> Dweezle Secnd Player, sign in--> Moon Unit What is the square root of 83.29097831183603 ? Dweezle, your guess: 9.1 Moon Unit, your guess: 9.2 The correct square root: 9.126389116832353 Dweezle is 0.026389116832353565 away Moon Unit is 0.07361088316764608 away Dweezle wins! What is the square root of 87.79346957866132 ? Moon Unit, your guess: 8.8 Dweezle, your guess: 8.9 The correct square root: 9.36981694477866 Dweezle is 0.46981694477866043 away Moon Unit is 0.5698169447786601 away Dweezle wins! What is the square root of 67.44682032701256 ? Dweezle, your guess: 8.2 Moon Unit, your guess: 8.1 The correct square root: 8.212601313044033 Dweezle is 0.012601313044033446 away Moon Unit is 0.11260131304403309 away Dweezle wins! What is the square root of 71.64725527288849 ? Moon Unit, your guess: 8.4 Dweezle, your guess: 8.45 The correct square root: 8.464470170831042 Dweezle is 0.01447017083104285 away Moon Unit is 0.06447017083104178 away Dweezle wins!
  • 39. Prepared by R. Arthy, AP/IT 39 ---- Final Score ---- Dweezle: 4 Moon Unit: 0 Call Scanner.nextLine() to read in the end of line characters after the number of iterations. Then read in the player names using Scanner.nextLine(). Use nextDouble() for the estimates. Math.abs() and Math.sqrt() will be useful. Exercise 9 — Pig-like Dice Game This is a dice game similar to the game Pig, but easier to implement. The player plays against the computer. 1. Player and Computer start out with zero points. 2. The winner is the first player to reach 100 points or more. 3. In each round, the computer rolls first, followed by the player. 4. The computer rolls three dice and the sum of spots is added to its score. 5. At the start of the player's turn, a working sum is initialized to zero. 6. The player then rolls a single die as many times as desired. o If the die shows a 1 (on the first roll or any roll), then the player's turn is over and nothing is added to the player's score. o For rolls other than 1, the roll is added to the working sum. o If the player stops rolling before a 1 occurs, then the working sum is added to the player's score. In a genuine Pig game, the computer would repeatedly throw a single die (just like the player) and use strategy to determine when to stop. Files Exercise 1 — Control Characters Write a program that writes ten x's to the screen (modify the HelloWorld.java program). Use file redirection to send the program's output to a text file. Use the DIR command (or in Unix, the ls -l command) to see how many bytes are in the file. Depending on how your operating system implements end of lines, you will see more than 10 bytes. C:>java Hello > output.txt C:>dir output.txt 08/13/99 07:01p 12 output.txt 1 File(s) 12 bytes 392,968,704 bytes free
  • 40. Prepared by R. Arthy, AP/IT 40 The additional two bytes are the control characters that indicate the end of the line. On a Windows system these control characters are carriage return followed by line feed. Exercise 2 — More Control Characters Modify the program so that it outputs 10 lines of 10 x's. Run it, redirect the output to a file, and examine the file. (It would be a very good idea to be sure that you don't have an infinite loop before you redirect the output to a file.) C:>java Hello > output.txt C:>dir output.txt 08/13/99 07:05p 120 output.txt 1 File(s) 120 bytes 392,968,704 bytes free The previous file has been replaced by a new file (with the same name). Exercise 3 — Appending to an Existing File Now run the original program 10 times in a row. In the first run create a new text file. With each additional run append the output to the first file. Check if the length is the same as in Exercise 2: C:>java Hello > output.txt C:>java Hello >> output.txt . . . . . . . . . . . C:>java Hello >> output.txt C:>dir output.txt 08/13/99 07:15p 120 output.txt 1 File(s) 120 bytes 392,968,704 bytes free The file has the same characters as the previous program that used a loop. Exercise 4 — Really Small File Now modify the program so that it outputs no characters. Redirect the output to a file. Is a file created (even though it contains no data?) What size is it? Exercise 5 — Text Editor Write a program that asks the user to enter lines of text. After each line the program echos the line to the terminal. The program finishes when the user enters a line that contains the characters //done (use a sentinel-controlled loop and the equals() method of class String.) Once the program is working, run it, and redirect the output to a file.
  • 41. Prepared by R. Arthy, AP/IT 41 If everything is working, try using your program to create a small Java source file by running the small editor and typing in the lines of the new program. You can correct mistakes as long as you are on the same line, but once you hit "enter" that line is committed. In the following example, the user creates the file Hello.java using the small editor, and then compiles and runs it. D:> java TextEdit > Hello.java class Hello { public static void main( String[] a ) { System.out.println("Hello new File!"); } } //done D:> javac Hello.java D:> java Hello Hello new FIle! What is going on: As far as Java is concerned, characters read from the terminal with Scanner.nextLine() are just ordinary characters that can be read into a string. While you (the user) are entering a line of characters from the keyboard you are interacting with the operating system. It is the operating system that allows you to edit a line with backspace, delete, and other characters. Once you hit enter, the OS sends the characters to Scanner. Note: this is a short program, about 15 lines, counting everything. If your program is getting to be longer than that, you are somehow making it more complicated than it needs to be. Exercise 1 — Sum of a file of Integers Write a program that adds all the integers in a file of text integers. This program will be similar to the ManySquares example program of the chapter and will use a similar input file. Prompt the user for the name of the input file. Exercise 2 — Average and Standard Deviation of a file of Doubles Write a program that computes the average and standard deviation of the text floating point numbers in a file. Use the following formulas for the average and the standard deviation of N values. The formulas compute the sum, the sum of squares, the average, the average square, the variance, and finally, the standard deviation. sum = x1 + x2 + x3 + ... + xN-1 + xN sumSQ = x1 2 + x2 2 + x3 2 + ... + xN-1 2 + xN 2 avg = sum/N avgSQ = avgSQ/N
  • 42. Prepared by R. Arthy, AP/IT 42 var = avgSQ - avg2 sd = var(1/2) The input file will contain any number text floating point numbers, similar to the following: 10.5 12.9 9.67 12.05 8.23 10.08 10.23 7.7 10.4 11.34 Numbers could be several, or none per line, and negative numbers are perfectly OK. For debugging purposes, use a file that contains one hundred values of 10.0. (You can easily make such a file using copy and paste with your text editor.) The average should be 10.0 and the standard deviation should be 0.0. Now try a file that contains fifty values 10.0 and fifty values -10.0. The average should be 0.0 and the standard deviation should be 10.0. Exercise 3 — Number Filter Write a program that reads integers from a text file. The program writes out the positive integers in the input file to one output file and the negative integers to a second output file. Prompt the user for the names of all three files. Exercise 4 — Separate Sums Say that a text file looks like this: x= 10 y= -45 y= 98 x= 13 x= 37 y= 36 x= -2 . . . Each line starts with "x=" or "y=" but which of these it starts with follows no pattern. Each of these is followed by a space then a single integer. Nothing else follows the integer on a line. Write a program that reads in this data file and computes the sum of the x values and the sum of the y values. Hint: use hasNext() and next() to read the "x=" and "y=" tokens and then use nextInt() to read the integer. You will also need the equals() method of String.
  • 43. Prepared by R. Arthy, AP/IT 43 Exercise 5 — Stop Word Remover Write a program that reads in a file of text, perhaps the text of a novel. The program copies the same text to an output file, except that all the useless words such as "the", "a", and "an" are removed. (Decide on what other words you with to remove. The list of words removed is called a stop list.) Do this by reading the text file token by token using hasNext() and next(), but only writing out tokens not on the stop list. Prompt the user for the names of the input and output files. Fairly Easy: The output file will have only N tokens per line. Do this by counting tokens as you output them. N will be something like 10 or 12. Improved Program: Preserve the line structure of the input file. Do this by reading each line using nextLine() and then creating a new Scanner for that line. (Look at the on-line documentation for Scanner.) With each line's Scanner, use hasNext() and next() to scan through its tokens. Harder: Write out no more than N characters per line. N will be something like 50. Do this by keeping count of the number of characters written out per line. The length() method of String will be useful. If X characters has already been written to the current line, and if X plus the length of the current token exceeds N, then start a new line. Exercise 6 — E-Mail Address Extractor write a program that scans a text file for possible e-mail addresses. Addresses look like this: someone@somewhere.net Read tokens from the input file one by one using hasNext() and next(). With the default delimiters of Scanner, an entire e-mail address will be returned as one token. Examine each token using the indexOf() method of String. If a token contains an at sign @ followed some characters later by a period, regard it as a possible e-mail address and write it to the output file. Programs such as this scan through web pages looking for e-mail addresses that become the targets of spam. Because of this, many web pages contain disguised e-mail addresses that can't easily be automatically extracted 1. Hard: Write a program that reads a text file that contains groups of integers that start with the word "next". For each group, the program computes and writes out the sum of integers in that group. There may be any number of groups. Example data set: next 12 45 92 -12 31 next 42 51 275 82 -274 -1 0 26 365 -56 72 next 90 93 91 95
  • 44. Prepared by R. Arthy, AP/IT 44 97 96 98 For this data the program writes: Sum of group 1 is 168 Sum of group 2 is 582 Sum of group 3 is 660 Here is another set of data: next 1 1 1 1 1 1 next next 1 1 1 1 1 1 1 1 1 next 10 11 12 13 7 8 9 For this data the program writes: Sum of group 1 is 6 Group 2 contains no data Sum of group 3 is 9 Sum of group 4 is 70 The logic of this program is quite tricky. 2. Long: Write a program that computes the average change of a value for each of several groups of data. Input is from a file of data. Size: about 80 lines, including blank lines and comments Time to Complete: part of an afternoon Problem: Say that your are conducting an experiment to determine the effect of a high fiber diet on cholesterol levels in humans. You have several groups of human subjects. At the beginning of the experiment the cholesterol level of each subject in each group is measured. Now the experiment runs for one month. Each group consumes a different amount of fiber each day. At the end of the month you want to see the change in each group's cholesterol level. The data for the experiment is in a text file like the following. Each line of the file contains a single integer (in character form). number of groups number of subjects in group 1 group1 subject1 starting cholesterol group1 subject1 ending cholesterol group1 subject2 starting cholesterol group1 subject2 ending cholesterol . . . . . group1 last subject starting cholesterol
  • 45. Prepared by R. Arthy, AP/IT 45 group1 last subject ending cholesterol number of subjects in group 2 group2 subject1 starting cholesterol group2 subject1 ending cholesterol . . . . . group2 last subject starting cholesterol group2 last subject ending cholesterol number of subjects in group 3 group3 subject1 starting cholesterol group3 subject1 ending cholesterol . . . . . group3 last subject starting cholesterol group3 last subject ending cholesterol . . . . number of subjects in the last group last group subject1 starting cholesterol last group subject1 ending cholesterol last group subject2 starting cholesterol last group subject2 ending cholesterol . . . . . last group last subject starting cholesterol last group last subject ending cholesterol For example, the following data file is for three groups. The first group has 2 subjects in it, the second group has 3 subjects in it, and the last group has 1 subject: 3 2 200 190 212 210 3 240 220 204 208 256 230 1 202 185 Assume that the data is correct (that the counts are correct and all the data is sensible and comes in complete pairs.) Write the program so that there is any number of groups (including zero) and so that a group can have any number of subjects in it (including zero.) You program should do the following: for each group compute and print out the average of the starting cholesterol values, the average of the ending cholesterol values, and the change in the averages. For example, with the above data your program should print out something like this: Group 1 2 subjects
  • 46. Prepared by R. Arthy, AP/IT 46 average starting cholesterol: 206 average final cholesterol: 200 change in cholesterol: -6 Group 2 3 subjects average starting cholesterol: 233 average final cholesterol: 219 change in cholesterol: -14 Group 3 1 subjects average starting cholesterol: 202 average final cholesterol: 185 change in cholesterol: -17 Done with processing. Notes: Use integer arithmetic throughout. If a group has zero subjects in it, report that fact but don't compute the averages (nor print them out.) It would be very helpful for you to plan this program in advance. The main organization of the program will be a counting loop inside of a counting loop. Use some well though out comments in your program to show how it is organized. Be sure that your indenting also shows how the program is organized. Here is another sample input file and its output: 4 5 230 210 230 215 230 220 230 225 230 230 3 210 200 210 200 210 200 0 2 200 190 210 200 Group 1 5 subjects average starting cholesterol: 230 average final cholesterol: 220 change in cholesterol: -10
  • 47. Prepared by R. Arthy, AP/IT 47 Group 2 3 subjects average starting cholesterol: 210 average final cholesterol: 200 change in cholesterol: -10 Group 3 0 subjects Group 4 2 subjects average starting cholesterol: 205 average final cholesterol: 195 change in cholesterol: -10 Done with processing. 3. Write a program that writes out a table of sines for angles -90.0 to 90.0 in increments of 15 degrees. Use one digit in the decimal fraction for the angle and 6 digits in the decimal fraction for the sine. Align the decimal points in both columns of numbers. angle sine ----- -------- -90.0 -1.0 -75.0 -0.965926 -60.0 -0.866025 -45.0 -0.707107 -30.0 -0.5 -15.0 -0.258819 0.0 0.0 15.0 0.258819 30.0 0.5 45.0 0.707107 60.0 0.866025 75.0 0.965926 90.0 1.0 To align its decimal point, treat zero degrees as a special case. 4. Write a program that calculates the value of a deposit for a given initial deposit, interest rate, times interest is calculated per year, and number of years. Use the formula: V = P(1 + r/n)nt V -- value P -- initial deposit r -- interest rate as fraction (eg 0.05) n -- number of times per year interest is calculated t -- number of years Prompt the user for P, r, n, and t. Write out the answer accurate to cents. Put a currency sign in front of the answer. Initial deposit: 100 Interest rate : 0.04 Times per year : 4 Number of years: 18 Value: $204.71 Make all variables doubles. Use the method Math.pow( double a, double b) from java.lang.Math which raises a to the power b.
  • 48. Prepared by R. Arthy, AP/IT 48 5. Write a program that calculates how many years it takes to double an amount of money for a given annual interest rate. Use the "Rule of 72" for this: divide 72.0 by the interest rate to get the approximate number of years it takes to double your money. For example, with 10% interest it takes about 7.2 years. Prompt the user for the interest rate, and write out the number of years, accurate to tenths. You might want to confirm the accuracy of this rule by using the previous program