Welcome to Week 3!

Learning Objectives of Today's Lesson

  • What is the Scanner object and how do you use it?
  • What is the java.util package?
  • What are the three necessary components of a complete interaction with a user of your program?
  • What are the 5 arithmetic operators in Java?
  • What is modulus (%) and why is it necessary?
  • What is the difference between integer and floating point division?
  • If time: What is the Math library and what are some of the operations it can perform.

Announcements

  • Return Quiz 1 after break
  • Quiz 2 on Thursday
    • 6 questions
    • 3 repeat questions from Quiz 1
    • 3 questions from lessons 4 - 5.
  • Lab 3 posted on CodeLab

Review Exercises

Find a partner and answer the following questions.


Part 1:
  • What are the four most common data types that we will be using in this class? Give an example of each.
  • Which of the following are correct examples of declaring a variable and assigning it a value?


    • Int numCats = 5;
    • double tempInF = 98.6;
    • double distance_to_school = 5 miles;
    • boolean 2coolForYou = False;
    • char myInitials5 = 'A';
    • boolean loveCode? = true;
    • char letters = 'XYZ';
    • int studentId;
      studentId= 555555;
    • int studentId;
      55555 = studentId;

                  


Part 2:

What Gets Printed to the Screen?

int oranges = 5;

int apples = 8;

int numFruit = apples + oranges;

System.out.println( "Total Fruit: " + numFruit);

oranges = oranges + 1;

apples = oranges;

System.out.println("Apples: " + apples);

System.out.println("Oranges: " + oranges);


Input and Output Cont'd

  • Another way to enter data into a variable is to read it from the console
  • The input console (keyboard) is called System.in
  • In Java, to read in data from the console, we need to create a Scanner variable (object).
        Scanner input;
  • You can envision the Scanner object "scanning" through the data that the user types into the keyboard.
  • In the above example, we name the Scanner variable "input".
  • We need to specify to the Scanner that it should be looking for data from the console (System.in).
    Scanner input = new Scanner(System.in);
  • Thus, we pass System.in as a parameter (i.e. put it inside the parenthesis) when we create the Scanner object.
  • We can then store the data we read in from the keyboard as a variable.
int numberOfDragons = input.nextInt();
  • In this example, whatever valid integer number the user types is stored in the variable numberOfDragons


Prompting Users

  • Good programming practice is to always "prompt" users for input like:

    public class Dragons {

        public static void main(String[] args) {
            
            //create a new Scanner named "input"
            //connect "input" to the keyboard, i.e. System.in
            Scanner input = new Scanner(System.in);
            
            //prompt the user
            System.out.print("Enter the number of dragons: ");
            
            //Take the next int entered by the user and store as numberOfDragons
            int numberOfDragons = input.nextInt();
            
            System.out.println("You entered: " + numberOfDragons + " dragons"); input.close();
        }
    }
    
    
  • Note that we do not put a newline after the prompt
  • The prompt waits on the same line for keyboard input as follows:
    Enter the number of dragons: |
  • Where the line above denotes where keyboard entry is made
  • Every user input should have a System.out.print prompt before it

A Word on Importing the Scanner Class

  • To use the Scanner to read data in from the console, we need to import the java.util.Scanner class from the java.util package
  • java.util.Scanner contains code that another programmer wrote to, for example, read user input from the keyboard.
  • We can import this class so that we do not have to write it for ourselves.
  • Once we import this class into our program, all we need to do is to learn how to use it.
  • We import the class by writing a statement like this:
import java.util.Scanner; //Scanner is class inside the java.util package

  • We place this line of code above the class name.

import java.util.Scanner;

public class Dragons {

    public static void main(String[] args) { //rest of main method


Methods for Scanner Objects for Numeric Data

  • When we use the Scanner object with numeric data, we need to specify the datatype: a double or an int.
  • For example:

Scanner input = new Scanner(System.in);

System.out.print("Enter the exam score (whole number): ");

int exam_score = input.nextInt();

System.out.print("Enter the GPA (decimal number): ");

double gpa = input.nextDouble();

  • Therefore, you must use the command that matches the datatype of your variable.
  • The two we will be using in this class are as follows:
double gpa = input.nextDouble();
int score = input.nextInt();


Activity 5.1: Calculating Your Weight on the Moon (10pts)

  • Find a partner for pair programming.
  • Open up Eclipse and create a new Java project named Moon with a class called Moon.java.
  • The objective of our program is to calculate a user's weight on the moon.
  • Add a block comment at the top of your program to include your names and section information.
/*
* @author Jennifer Parrish
* @author Georg Albrecht
* CIS 36A
*/
  • Now add a statement to import the java.util.Scanner library at the top of your program

import java.util.Scanner;

  • You can place this above the class declaration.

import java.util.Scanner;

public class Moon {

  • Declare a new variable to capture the user's weight. Name your variable weight.
  • What data type do we need here? Why?
  • Declare your variable at the top of main.
  • Now, let's output a message to the screen explaining to the user the purpose of our program.
Welcome! Let's calculate your weight on the moon!
  • Run your program to make sure it works and you get the output you expected.
  • Now, we need another System.out.print statement to prompt the user to enter his or her weight. Add this statement right below the last System.out.println statement.
Please enter your weight in pounds: |
  • Make sure that you have left a space right before the second set of quotation marks to allow space for the user to type his or her answer.
  • Now, run your program again to ensure you haven't made any errors.
  • Next, we need to declare a new Scanner variable to capture the user input from the keyboard:
Scanner input = new Scanner(System.in);

  • Next, let's read the user input and store it as the weight variable.
  • Hint: will you need nextInt() or nextDouble()? Recall that you need to match the datatype of your variable.

weight = input.next??????

  • Using the weight entered by the user, we need to calculate the user's weight on the moon. To calculate his or her weight on the moon, we divide his or her weight on earth by 6. Write the following statement:
weight = weight / 6;

  • Finally, we need to display our results to the user. Add a new System.out.println statement like the one below:
System.out.println( "Your weight on the moon is: " + weight);

  • Run your program to calculate your weight on the moon!
  • Finally close the Scanner:

input.close();

  • Submit your Moon.java to Canvas when you are finished. Note: Both partners need to submit for full credit.

Arithmetic Operators and Expressions

How Do You Represent Negative and Positive Numbers in Java?
  • +/- Integers
    • -123456
    • 123456
  • +/- Decimal Numbers
    • -12345.678
    • 12345.678
  • Simply put a - sign in front of a number to make it negative

Arithmetic Operators - Add, Subtract, Multiply and Divide

  • Addition: +
    • int sum = 5 + 6;
  • Subtraction: -
    • double difference = 8.1 - 3.9; 
  • Multiplication: *
    • double product = 2.9 * 6.3;
  • Division: /
    • int quotient = 6 / 2;
But, wait! There's one more operator... Introducing modulus...
  • Modulus: %
    • The remainder when you divide.
    • Represented as the % sign.
    • Counter-part to integer division.
    • int remainder = 12 % 5;
Order of Operations
  • Remember PEMDAS from your math classes? Please Excuse MDear Aunt Sally
Parenthesis
Exponents
Multiplication
Division
Addition
Subtraction
  • To change the order of operations, you use parentheses
  • For example:
    is written as: a + b / 2
    is written as: (a + b) / 2

Notes About Arithmetic

  1. You can use parentheses to group expressions
    • Anything within the parentheses is evaluated first
      2 * (10 + 5)
  2. You can have parentheses within parentheses
    • Innermost parenthesis evaluated first
      (2 * (10 + 5))
  3. Parentheses cannot be used to indicate multiplication
    • Invalid expression: (2)(3)
    • Must use the * operator

Programming Style

  • Programming style: add spaces around binary operators
    • 2 + 3, not 2+3
  • Programming style: no spacing after opening or before closing parenthesis
    • (2 / 3), not ( 2/3 )


Mixed-Mode Expressions

  • Recall that different data types are stored in different forms
    • An int is stored in 4 bytes
    • double is stored in 8 bytes
    • The format they are stored in is different as well
  • The computer needs both operands in the same form before it can perform an operation
  • If one operand is different than the other, the compiler converts it to the wider of the two types
  • For example:
    2 + 2.3
  • First number (2) is an int
  • Second number (2.3) is a double
  • Java will automatically convert an int to a double
  • Then the arithmetic operation can take place to produce a result of 4.3
  • Remember that the result of arithmetic with an int and a double is a double

Integer Division and Modulus

  • Dividing two integers can produce unexpected results for the unwary
  • In division, if at least one of the numbers is a floating-point number, the result is a floating point number:
    7.0 / 2.0   // 3.5
    7 / 2.0     // 3.5
    7.0 / 2     // 3.5
    
  • However, if both numbers are integers, then the result is an integer:
    7 / 2       // 3
    
  • The decimal remainder is truncated (cut short, discarded, thrown away)
  • To get the integer remainder of division between two integers, you use the modulus operator: %
    7 % 2       // 1 (remainder)
    
  • 7 % 2 returns 1 because 1 is the remainder when 7 is divided by 2:
        3  r 1
    2 ) 7
       -6
        1 remainder 


Activity 5.2: Arithmetic (10 pts)

Through the miracles of computer science, we will now convert your $1000 computer into a $10 calculator! Along the way, we learn how to work with arithmetic using Java.

Specifications

  • Find a partner for pair programming.
  • Open up Eclipse and create a new project called Arithmetic with a class called Arithmetic.java.
  • Add a block comment to contain your names and section information:
/*
* @author name of partner1
* @author name of partner2
* CIS 36A
*/

  • Within the curly braces of the main method, declare two double variables named a and b, and assign them a value of 7 and 2 respectively. For instance:
    double a = 7, b = 2;
  • Add a line of code to display the arithmetic expression (a + b) and then recompile and run the program.
    System.out.println("a + b = " + ( a + b ));
    

    The output when you run the program should look like this:

    a + b = 9.0
    

    If you do not see this output, please ask a classmate or the instructor for help.

  • Note the use of the () around a+b to indicate that we need to sum a and b before we print out the message to the console.
  • Add three more lines of code like the previous one that computes the expressions: a - ba * b and a / b. Compile and run your program again and make sure your program now displays the following output:
    a + b = 9.0
    a - b = 5.0
    a * b = 14.0
    a / b = 3.5
    
  • The order of operations matters in Java just like it does in algebra. Multiplication and division are performed before addition and subtraction. Add the following two statements to your program:
    System.out.println("a + b / 2 = " + (a + b / 2));
    System.out.println("(a + b) / 2 = " + ((a + b) / 2));
    
  • Compile and run your program again and compare the output. Your program should now display the following output:
    a + b = 9.0
    a - b = 5.0
    a * b = 14.0
    a / b = 3.5
    a + b / 2 = 8.0
    (a + b) / 2 = 4.5
    

    Note how the output of the two statements is different. You can change the order of operation using parenthesis, just like in algebra.

    As you can see, arithmetic in Java works much like you would expect. However, there are some mysteries when working with integer variables which we will now explore:

    • Truncation in integer division
    • Modulus (%) operator

  • Truncation in integer division: Change the data type of the two variables from double to int, like this:
    int a = 7, b = 2;
  • Compile and run your program again and compare the output. Note how the result of the division operation changed. What happened to the decimal part of the result?

    In programming terms, we say that the decimal part is truncated (cut short). You have to watch out for this in Java programming or you may get unexpected results in your calculations. 

  • Modulus (%) operator: Sometimes we want the integer remainder from an integer division. To see the integer remainder, we use the modulus (%) operator. Add the following statement to your program:
    System.out.println( "a % b = " + (a % b));
    
  • Compile and run your program again with this added statement. Your program should now display the following output:
    a + b = 9
    a - b = 5
    a * b = 14
    a / b = 3
    a + b / 2 = 8
    (a + b) / 2 = 4
    a % b = 1
  • Mathematical functions: More complex mathematical operations require the use of a method in Java. One such method is sqrt(number) which calculates the square root of the number inside the parenthesis. Add the following statement to your program:
    System.out.println("sqrt(a + b) = " + Math.sqrt(a + b));
    
  • Note the use of the word Math in front of the sqrt function.
  • The word Math indicates that the compiler should look for the sqrt function inside the Math class.
  • Compile and run your program again with this added statement. Your program should now compile and display the following output when run:
    a + b = 9
    a - b = 5
    a * b = 14
    a / b = 3
    a + b / 2 = 8
    (a + b) / 2 = 4
    a % b = 1
    sqrt(a + b) = 3.0
    

    For more information on mathematical methods see the section below.

  • Save your program source code that displays all eight (8) expressions and submit it to Canvas.

Completed Program

Once you are finished, your source code should look like the following:


Mathematical Methods

  • Operators provide only the simplest mathematical operations
  • For more complex mathematical operations, we use methods defined in the Math class.
  • java.lang.Math class contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.
  • A Java method is like a math function that takes an argument ("input") and produces ("returns") a value
  • For example:
    double square_root = Math.sqrt(9.0);
  • In the above example, the input is 9.0 and the Math.sqrt() method returns the square root of the argument
  • Java has a class named Math that contains many such methods.
  • Math is part of the java.lang package which is automatically imported into your program.
  • Therefore, to use the Math class, all you need to do is to append the word Math in front of your mathematical methods.
  • Some of the functions are listed below
  • Note that many of these functions are designed to work with floating-point date types like double
NameDescriptionExampleResult




expexponential (ex)Math.exp(1.0)2.71828
lognatural logMath.log(10.0)3.10259
powpowers (xy)Math.pow(2.0, 3.0)8
sqrtsquare rootMath.sqrt(4.0)2
sinsineMath.sin(0)0
coscosineMath.cos(0)1
  • In addition, the Math class includes two similar functions: ceil, and floor
NameDescriptionExampleResult
ceilceiling: round upMath.ceil(3.0001)
Math.ceil(3.7)
4.0
4.0
floorfloor: round downMath.floor(3.3)
Math.floor(3.9999)
3.0
3.0
  • Both return whole numbers, although they are of type double
  • Why might this be the case?

Using Mathematical Methods

  • How are mathematical methods evaluated?
  • Whatever is within the parenthesis of the function call is evaluated first
  • Thus, in the following example, we get the square root of 9.0
    double square_root = Math.sqrt(3.0 * 3);
  • If the method is used in an arithmetic expression, they are handled just like a number of the type returned
  • For example, in the following, the value 4.0 is stored in the double variable num:
    double num = 1 + Math.sqrt(3.0 * 3.0);
    System.out.println(num);
    
  • Note that the method evaluates the Math.sqrt(3.0 * 3) before adding it to 1.0
  • Thus methods have a higher precedence than arithmetic operators.


Group Activity:

  • Take out your calculator program and add some more calculations to it.
  • You should add calculations using at least 3 of the functions above (your choice).
  • For example, might add the following:

System.out.println("pow(a, b) = " + Math.pow(a, b));

  • When you are finished, find a partner and answer the questions below.


Upcoming Assignments

~See You Thursday!~