CS 1063  Week 8:  Fundamental Data Types

The Assignment Statement and Console Input

Objectives

Assignments

Numeric data conversion

In Java, conversions can occur in three ways:

  1. 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:
    char ch;  // can hold the value of a single character
    int i;    // can hold an integer value up to plus or minus 2 billion
    double d; // can hold 15 significant digits up to plus or minus 10300
    ch = 'A'; // stores the character A in ch
    i = ch;   // stores the numeric value of A (65) in i
    d = i;    // stores 65.0000000000000 in d (promotion in assignment)
    
  2. 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.
  3. 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

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.  The form is 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.
s1 = s + vt + 
 1 

2
 gt2 
G = 4 pi2  
a3

 p2(m1 + m2) 
future Value = present Value ( 1 +  
 interest 

100
 )yrs 
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 fields (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.

It will also be useful to includes some constants.

final double NICKEL_VALUE = 0.05;
final double DIME_VALUE = 0.1;
final double QUARTER_VALUE = 0.25;

2.  Create your project and begin implementing the class using method stubs (methods without the code) and comments describing what the methods will do.

Setup: 3.  Implement the constructors and methods using the comments you wrote for the method stubs.  Run your project to check for any errors.

4.  Test your class.  Write the main method of PurseTest.java .

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 part 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 or above:

Put this import statement at the top of your test class.

import java.util.Scanner;

This is an example of code within a main method.

Scanner in = new Scanner(System.in);
System.out.print("How many nickels do you have? ");
int quantity = in.nextInt();

These are some methods in the Scanner class that we will use often.

OR

Example for previous Java versions:

Put these import statements at the top of your test class.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

Add this to the signature of the main statements at the top of your test class.

throws IOException

This is an example of code within a main method.

BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String input;

// Reading a double
System.out.print("Enter the amount in your purse: ");
input = console.readLine();
double amount = Double.parseDouble(input);

// Reading an integer
System.out.print("Enter the number of nickels: ");
input = console.readLine();
int numNickels = Integer.parseInt(input);

// Reading a String
System.out.print("Enter the name of the student: ");
String name = console.readLine();

Examples of reading console input using the BufferedReader class