CS 5063
Day 8: Fundamental Data Types
The Assignment
Statement, Console Input and
Decisions
Objectives
- Write arithmetic expressions in Java
- Design and implement the Purse
class
- Read input from the console
Assignments
Numeric data conversion
In Java, conversions can occur in three ways:
- Assignment conversion (the value of the expression on
the right has to be converted to agree with the type of variable on the
left). For example:
int i;
double d;
char ch;
i = 3;
d = i; // stores a copy of i in d (promotion in assignment)
i = 'A'; // stores the numeric value of A (65) in i
- Arithmetic promotion (the operands of an operation need
to be in the same format before the operation can be performed). For
example, in
8.0 * 5 the 5 is
converted/promoted to a double before the
multiplication, resulting in the value 40.0 rather than 40.
Watch out for precedence: the expression (40.0 - 32.0)* (5/9)
evaluates to 0.0.
- Explicit casting for type conversion
int n = 20;
int d = 8;
double ans;
ans = n/d; // 2.0 is stored in ans. If both arguments of the / operator are integers, the result is an integer and the remainder is discarded.
In the case below n is first promoted to a
double and then
the division occurs.
ans =
(double)n/d; // 2.5 is
stored in ans
What is stored in ans
after the following code is executed?
ans = (double) (n/d);
Comparing Primitive Types and Objects
Primitives used: int, double, char and boolean
- Primitive variables hold values. Object variables
hold references
- A copy of an object reference is another reference to the same object
The Math class
The Math class allows you to perform common math
functions --- like taking the square root or raising to a power. Math
doesn't store any data --- it just does calculation. Math
is an example of a static class.
You don't need to create a
Math object to call Math's methods. A static
method does not operate on an object. Example ClassName. methodName(parameters)
double z = Math.sqrt(y); // find the square root of y
double w = Math.min(y, z); // find the minimum of the values in y and z
double p = Math.pow(3,4); // calculate and return the value 3*3*3*3 = 81
System.out.println(Math.abs(x)); // output the absolute value of x
Activity 1: Arithmetic and Mathematical Functions
Write the following mathematical expressions in Java.
1
s1 = s + vt + ___ gt2
2
a3
G = 4 pi2 _______________
p2(m1 + m2)
interest
future Value = present Value ( 1 +
________ ) yrs
100
What is wrong with this version of the quadratic formula?
x1 = (-b - Math.sqrt(b * b - 4 *
a * c))/ 2 * a;
x2 = (-b + Math.sqrt(b * b
- 4 * a * c))/ 2 * a;
Activity 2: The Purse Class
Public Interface for the Purse
Class
public Purse()
// Constructs an empty
purse
public void addNickels(int count)
// Add nickels
to the purse
// count - the
number of nickels to add
public void addDimes(int count)
// Add dimes
to the purse
// count - the
number of dimes to add
public void addQuarters(int count)
// Add
quarters to the purse
// count - the
number of quarters to add
public double calculateTotal()
// calculate
the
total value of the coins in the purse
// return the
sum of all coin values
1. Determine the instance
variables(data) for
your class. Determine what
information an object needs to store to do its job. List beside each method from
public interface the information that is necessary to complete the
task.
Constants
- A final variable is a constant. Once its value has been
set, it cannot be changed.
- Use named constants to make your programs easier to read and
maintain
- Constants are declared with all caps usually located above the
instance variables
final double NICKEL_VALUE = 0.05;
final
double DIME_VALUE = 0.1;
final
double QUARTER_VALUE = 0.25;
2. Creating your project
and implementing the class using methods without the code and comments
describing what the method will do.
Setup:
- Project/Package name: pursepkg
- New main class: PurseTest
- New class (be sure to uncheck main method here): Purse
- Save all
- Run -> right click on the file PurseTest and chose run using
defaults
3. Implementing the
constructors and methods using the comments you wrote in the
shell. Run your project to check for any errors.
4. Write a second class to
execute the test instructions below
instantiate a new purse object
named aPurse
- add 3 nickels to aPurse
- add 1 dime to aPurse
- add 2 quarters to aPurse
- get the total value of the money in the purse and store this
value in a double variable totalValue
and print this value with an appropriate label.
Activity 3 Enhancing the Purse Class
1. Enhance the Purse class
by adding methods addPennies
and addDollars.
2. Add a private method toPennies to the Purse class. toPennies should calculate and
return the total value of all of the coins as an integer. For
example if the total value of the coins is $2.14 then this method
should return 214.
3. Add methods getNumDollars
and getNumCents to the Purse class. The getNumDollars method should
return
the number of whole dollars in the purse, as an integer. The getNumCents method should
return
the number of cents, as an integer. For example, if the total
value of the coins in the purse is $2.14, getNumDollars returns 2 and getNumCents returns
14. Refer back to common uses of
the mod operator.
Use your private method you wrote in #2 and the following constant to
do these calculations.
final int
PENNIES_PER_DOLLAR = 100;
4. Modify the PurseTest
class by asking the user to enter the number of pennies,
nickels, dimes, quarters and dollars to add to the purse.
Reading Console Input and testing your
enhancements
Use the Scanner class to read
keyboard input in a console window.
|
Example for Java 5.0:
import java.util.Scanner;
Scanner in =
new Scanner(System.in);
System.out.print("How many nickels
do you have? ");
int quantity =
in.nextInt();
Some methods in the Scanner class that we will use often.
- public String
nextLine() Returns as a character string all input remaining on
the current line.
- public double nextDouble()
- public int nextInt()
Examples
Reading a double
System.out.print("Today's Sales store 1 ");
String input = in.readLine();
double store1 = Double.parseDouble(input);
Reading an integer
System.out.print("Enter the number of stores ");
String input = in.readLine();
int numStores = Integer.parseInt(input);
Reading a String
System.out.print("Enter the name of the student ");
String name = in.readLine();
OR
Example for previous Java versions
import
java.io.BufferedReader;
import
java.io.InputStreamReader;
import
java.io.IOException;
throws IOException
added to the main heading.
BufferedReader
console = new BufferedReader(new
InputStreamReader(System.in));
Examples of
reading console input using the BufferedReader
class
Break
Boolean expressions with relational operators
A boolean expression is one that has a value that is
either
true or false. Use a boolean
variable
to hold the value of a boolean expression.
A relational operator is one that compares two values.
(In
contrast to an arithmetic operator that combines two values to produce
a
new arithmetic value.)
Relational operators
|
Symbol
|
Meaning
|
Example
|
==
|
equal to |
if ( a == 5 ) |
>
|
greater than |
if ( salary > 30000 ) |
<
|
less than |
if ( 0 < salary ) |
!=
|
not equal toi |
if ( a != b ) |
>=
|
greater than or equal to |
if ( salary >= 10000 ) |
<=
|
less than or equal to |
if ( 20000 <= salary ) |
- The two operands of a relational operator should be the same
data type,
although Java does allow some mixing of types.
- Relational operators return a true or false
answer
- Note difference between test for equality (
==) and
the assignment operator (=).
- When comparing floating-point numbers, don't test for
equality. Instead, check whether they are close enough
Assume that x and y are double values and that
the constant EPSILON = .00001
The following statement will compare x and y and determine is they are
"close" enough
if( Math.abs( x - y ) <=
EPSILON
The if and if/else statements
| The if statement lets a
program carry out different actions depending on the outcome of a
condition. |
One consequent:
if (condition)
truestatement;
Two alternatives:
if (condition)
truestatement;
else
falsestatement;
Examples of using just an if
statement:
if ( numGrades != 0 )
average = sum/numGrades;
if( amount <= balance )
balance = balance - amount;
Examples of using the if/else
statement:
if ( value >= 0 )
System.out.println("square root of " + value + " = " + Math.sqrt(value));
else
System.out.println("nonpositive number " + value + " entered");
if ( amount <= balance )
balance = balance - amount;
else
balance = balance - OVERDRAFT_PENALITY;
| A block statement groups
together several statement |
Example: What does the following do? (Trace with variables)
if ( x > y ){
temp = x;
x = y;
y = temp;
}
In the above example more than one statement is included in the
consequent, so we use curly braces ({}) to group them.
Activity 4
- Assign theMin to be
the smallest of x and y
- Write an if
statement that assigns 100 to x when y is equal to 0.
- Write an if-else
statement that assigns 0 to x when y is equal to 10. Otherwise it
should assign 1 to x.
- Write an if
statement that sets the variable hours to 10 when the boolean variable minumum is equal to
true
- Calculate wages as hoursWorked
times hourlyRate with
time and a half for overtime( hours over 40)
Activity 5 The QuadraticEquation
Class
Write a program that prints all real solutions to
the quadratic equation ax2 + bx + c = 0. Read in a,b,c
and use the quadratic formula. If the discriminant b2
- 4ac is negative, display a message stating that there are no real
solutions.
Implement the class QuadraticEquation
whose constructor receives the coefficients a, b, and c of the quadratic
equation. Supply methods calculateSolution1
and calculateSolution2
that get the solutions, using the quadratic formula. Supply a
method boolean
hasSolution() that returns false
if the discriminant is negative and true otherwise.
Setup:
- Project/Package name: quadraticequationpkg
- New main class: QuadraticEquationTest
- New class (be sure to uncheck main method here): QuadraticEquation
- Save all
- Run -> new -> browse (...) -> chose the file QuadraticEquationTest
->
ok
Test your class by asking the user to enter values for a, b and
c. Remember that you must use hasSolution before you call calculateSolution1 and calculateSolution2. Find
3 values that produce the message no real solution and 3 values that
have a solution
Last
Modified: May 15,
2007 at 11:48am