Lab 2 Assignments, Expressions & Reading User Input with “Scanner”

advertisement
Lab 2
Assignments, Expressions & Reading
User Input with “Scanner”
The purpose of this lab is two-fold: to write programs that use variables, assignments and
expressions, and to practice reading input from users using a Java class named “Scanner”.
Since “Scanner” is a built-in Java class, we will also learn how to access the Java Class
Library with a web browser, and how to find the methods that can be used to read user
input.
To store the programs you will write in this lab, create a folder named “lab02” in your
computer.
Once you have completed a section, you should submit to the appropriate WebCat
assignment for grading.
Technical Section
A. The Java Class Library
Java comes packed with hundreds of classes that we can reuse in our programs. To have
an idea of the many classes that are predefined in Java, use your web browser to go to the
address provided by your instructor where the Java library is located. Write this address
below
**Java Class Library URL: < http://java.sun.com/javase/7/docs/api/>
This web page shown should look like the one in Figure 1. It shows (on the lower-left
frame) the list of all the classes in the library. Selecting a class on this frame will display
detailed information about that class on the main right-left frame. In the case of the figure
shown, the class “Scanner” has been selected and its information is displayed on the right
frame.
Figure 1. Scanner class
1. The “Scanner” class
Up to this point, the programs we wrote executed from beginning to end without
stopping. They could do that because all the data they needed was written in the source
code. The problem with this approach is that every time we want to use different data we
have to modify the source code with new values, compile and then run the program to see
the results. If this is a cumbersome process for us programmers, you can imagine it would
impossible for non-programmers to do.
Instead, we should create programs that pause and ask the user for the information to
handle; generalizing our program to work for any combination of data with a simple
program change. This is what “Scanner” can do for us, since it has methods that capture
data from the keyboard.
For example, when the following program is executed, it requests two numbers from the
user and prints the sum of these numbers, as it is shown in Figure 2.
1
2
3
4
5
6
7
8
9
10
11
import java.util.Scanner;
public class Sum {
public static void main(String[] args) {
Scanner in = new Scanner( System.in );
System.out.print( “Write the first number: ” );
int one = in.nextInt();
System.out.print( “Write the second number: ” );
int two = in.nextInt();
System.out.println( “The sum of ” + one + “ and ” + two + “ is ” + (one + two));
}
12
}
Figure 2. Example of Sum.java execution
The code above declares and initializes a new “Scanner” variable called “in” (line 4) that
can read from the keyboard (“System.in”). This variable is used for reading integer
values using Scanner’s “nextInt” method (lines 6 and 8). When executed, “nextInt” stops
the execution of the program until a number followed by <Enter> has been inputted.
Using your web browser, find “Scanner” in the Java library and write the description of
its method “nextInt()” (choose the method that does not receive any parameters).
________________________________________________________________________
Also part of this class is the method “nextDouble()”. Find its description and write it
below.
________________________________________________________________________
What is the difference between the value returned by “nextInt” and “nextDouble”?
B. Program testing
As you begin to learn how to program, it is important to develop a habit of properly
testing a program. To put it in proper focus, the basic steps are:
1. design
2. write the program
3. test the program
Having a program that runs and gives answers is not sufficient. It is necessary to be sure
that your program calculates the right answers. In many instances, a number of different
scenarios must be considered. For example, if one created a payroll system, in order to
test if the program correctly handles overtime pay the testing must include a case for
someone working:

< 40 hours in a week

> 40 hours a week

exactly 40 hours a week (this is called a boundary condition).
Realize that any testing you do is incomplete, but it is important to do your best to create
a good test set. In these examples, you have been given some test sets to use with your
applications, but you will eventually be required to define your own tests.
Programming Section
A. System.out.println
In lab 1, we used “System.out.println” to write our name to the screen, and the “+”
operator to concatenate different strings. In addition, when it is used with strings, “+” can
concatenate values and variables of other types as well (such as “int” and “double”) to
create larger strings. For example, when the following code is executed
1
2
3
4
5
6
7
8
public class Println {
static public void main(String[] args) {
String name = "Thomas Jefferson";
int born = 1743;
int died = 1826;
System.out.println( name + “ lived ” + (died-born) + “ years, from ” + born + “ to ” + died);
}
}
it displays the text shown below.
You can use this approach when outputting string and numeric values to the screen. Now
let’s begin calculating the area of shapes.
B. Exercise: The Area of Shapes
In this first exercise you will create 3 programs that calculate the area of three shapes:
rectangles, triangles and circles.
To this end, open jEdit (if you haven’t done so already) and create a new document. Save
it in the “lab02” directory with the name “RectangleArea.java”.
Write in this file a class named “RectangleArea” containing a “main” method. In this
method, you will define local variables holding the dimensions of a rectangle, a triangle
and a circle, will use “Scanner” to read these dimensions, will write expressions
calculating their areas, and will display these values and their results to the screen.
As you complete each program, note that most of the activities require you to submit the
program to WebCat for grading. If you have not been able to successfully submit to
WebCat, see your instructor.
Also pay close attention to the format of your output. Programs that are not formatted
correctly are viewed as incorrect even if the calculations produce the right answers.
Lab 2A. The Area of a Rectangle
The area of a rectangle is found by multiplying its base and height.
As such, define 3 integer variables in “main”: two for the base and height, and one for
the area.
Your program should read the base and height using the following format
Rectangle’s base: 7
Rectangle’s height: 6
…and it should write to the screen in the following format
The area of a rectangle of base 7 and height 6 is 42
An example run of the program should look as illustrated below.
Testing
Test that your program calculates areas correctly by using the following values



base = 11, height = 15, area = 165
base = 19, height = 7, area = 133
base = 231, height = 57, area = 13167
Also try other values to see if they give correct results.
Lab2 A
Submit your program to Web-CAT for evaluation.
BE PRECISE WITH THE FORMAT OF YOUR OUTPUT!!! Web-Cat is an
automatic grader that examines the output for correctness expecting you to follow
specifications precisely.
Lab 2B. The Area of a Triangle
Continue by creating another program named “TriangleArea.java” which should contain
operations to calculate the area of a triangle. The program will be very similar to the last
one so you might want to try copying the previous one and making appropriate changes
rather than writing the entire program from the beginning. Name the class
“TriangleArea”.
The area of a triangle is found by multiplying its base and height and dividing this result
by 2.
As such, define 3 variables in “main”: two integers for the base and height, and one
double for the resulting area.
Your program should read the base and height using the following format
Triangle’s base: 21
Triangle’s height: 3
…and should write to the screen in the following format
The area of a triangle of base 21 and height 3 is 31.5
Testing
Test that your program calculates areas correctly by using the following values



base = 7, height = 8, area = 28.0
base = 9, height = 42, area = 189.0
base = 97, height = 13, area = 630.5
Note: the type (int versus double) of the variables needed for this program have changed.
One could argue that the two inputs in the RectangleArea program should be double
(even though you were directed to use int), but even if the triangle base and height are int,
the area should be declared as double as indicated by the results for the test cases.
Choosing the appropriate data type for your variables is an important part of the design.
Lab2 B
Submit your program to Web-CAT for evaluation.
Lab 2C. The Area of a Circle
The area of a circle is found by multiplying the square of its radius by π. For simplicity,
assume that the value of π is 3.14159. The square of the radius is calculated by
multiplying it by itself.
As such, define 2 double variables in “main”: one for the radius, and one for the area.
Create another program named “CircleArea.java”. Your program should read the radius
using the following format
Circle’s radius: 5
…and write to the screen in the following format
The area of a circle of radius 5.0 is 78.53975
Testing
Test that your program calculates areas correctly by using the following values



radius = 2.1, area = 13.8544119
radius = 7.44, area = 173.898316224
radius = 19.0, area = 1134.11399
By now, your program should look like shown in the following screen shot.
Lab2 C
Submit your program to Web-CAT for evaluation.
C. Exercise : Subtle Calculations (using integers).
Lab 2D. Fahrenheit to Celsius (and vice versa)
In this exercise we will calculate a temperature in Celsius given a Fahrenheit value, and a
Fahrenheit value given a Celsius temperature.
The formulas to translate between Celsius (oC) and Fahrenheit (oF) are
For this exercise, create a jEdit text file and save it in the “lab02” folder under the name
“Temperature.java”. Write in this file a “Temperature” Java class with a “main”
method.
The method should have 4 double variables (a Fahrenheit variable and its resulting
Celsius temperature, and a Celsius variable and its corresponding Fahrenheit
temperature), should input a Fahrenheit temperature and display the corresponding
Centigrade temperature, and then input a Centigrade temperature and display the
corresponding Fahrenheit temperature information in the following format (where o is a
lower case O, the letter).
86.0 oF = 30.0 oC
-40.0 oC = -40.0 oF
An example run of the program should look as illustrated below.
Be careful to check your answers: fractions may not behave as expected.
Testing
Test that your program translates temperatures correctly by using the following values




32 oF = 0 oC
107.6oF = 42.0 oC
14 oF = -10.0 oC
-22 oF = -30.0 oC
If your program is producing answers that are 0, watch the video for dividing integers for
help.
Lab2 D
Submit your program to Web-CAT for evaluation.
D. Exercise : Do You Have Any Change?
The goal of this exercise is to identify the dollars/coins that can be used to give change to
customers from a vending machine using 1 dollar bills, quarters, dimes and cent coins.
For our problem assume you have no nickels in the machine. For example, if a customer
pays $35.00 for a purchase of $32.27, your program should find that the change should be
2 dollars 2 quarters, 2 dimes and 3 cents.
Using jEdit, create a new Java file named “Change.java” and save it the “lab02”
directory. Write in this file a “Change” Java class with a “main” method. Define variables
to hold the amount of the purchase, the money the customer puts in the vending machine
and variables for the number of dollars, quarters, dimes and cents.
Your program should input the amount of the display this information in the following
format
Given $35.00 for a purchase of $32.37 we need
2 dollars
2 quarters
2 dimes
3 cents
(if none of a specific coin is needed, print 0)
This problem is more challenging. A number of programming concepts are raised including:
when to use integers versus double, casting a value. repetition of similar processes, and the
critical nature of order of the operations. Ask your instructor if you need more assistance.
An example run of the program should look as illustrated below.
Testing
Test that your program breaks amounts correctly by using the following values





Given $1.09 = 1 dollars 0 quarters 0 dimes 9 cents
Given $0.95 = 0 dollars 3 quarters 2 dimes 0 cents
Given $ 25.00 = 25 dollars 0 quarters 0 dimes 0 cents
Given $ 2.72 = 2 dollars 2 quarters 2 dimes 2 cents
Given $ 1.84 = 1 dollars 3 quarters 0 dimes 9 cents

Lab2 E
Submit your program to Web-CAT for evaluation.
ALL OF YOUR SUBMISSIONS FOR THIS LAB ARE TO BE SUBMITTED TO
WEBCAT.
YOU SHOULD CHECK YOUR RESULT
Download