[go: up one dir, main page]

0% found this document useful (0 votes)
58 views81 pages

Unit 1 Primitive Types

This document introduces primitive data types in Java like int, double, and boolean that are used to store numeric and boolean values. It explains variables which are named locations in memory used to store values, and how variables are declared with a type and then assigned a value. The receipt example shows how to calculate a total using variables to store subtotal, tax, and tip amounts rather than repeating expressions.

Uploaded by

Hyon Park
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views81 pages

Unit 1 Primitive Types

This document introduces primitive data types in Java like int, double, and boolean that are used to store numeric and boolean values. It explains variables which are named locations in memory used to store values, and how variables are declared with a type and then assigned a value. The receipt example shows how to calculate a total using variables to store subtotal, tax, and tip amounts rather than repeating expressions.

Uploaded by

Hyon Park
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 81

Unit 1: Primitive Types

Basic Java Syntax


Adapted from:
1) Building Java Programs: A Back to Basics Approach
by Stuart Reges and Marty Stepp
2) Runestone CSAwesome Curriculum

This work is licensed under the


Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

https://longbaonguyen.github.io
Java

What do Minecraft, Android phones, and Netflix have in


common? They’re all programmed in Java!

Many of the apps you use in an Android phone or tablet are also
written in Java. Java is used worldwide to create software that
we all use.

2
Java
Java is a programming language, which means that we can
use Java to tell a computer what to do.

Computers don’t actually speak Java so we have


to compile (translate) Java source files (they end in .java) into
class files (they end in .class).

The source file is something humans can read and edit, and the
class file is code that a computer can understand and can run.
3
Java Terminology
• class:
(a) A module or program that can contain executable
code.
(b) A description of a type of objects. (Animal class,
Human class, Employee class, Car class)

• statement: An executable piece of code that represents a


complete command to the computer.
– every basic Java statement ends with a semicolon ;

• method: A named sequence of statements that can be


executed together to perform a particular action or
computation.
4
Structure of a Java program
public class name { class: a program
public static void main(String[] args) {
statement;
statement; method: a named group
... of statements
statement;
}
} statement: a command to be executed

• Every executable Java program consists of a class, called the


driver class,
– that contains a method named main,
• that contains the statements (commands) to be executed.
5
First Program on BlueJ
We will use BlueJ an integrated development environment(IDE),
for the first part of this course to write all of our code.
compile: Must click. Click to run
main method

console: Text box into which


the program's output is printed.

6
File naming
The name of the class has to match up with the name of the file.

For example, the class below is called Main therefore the name
of the file is Main.java. The main class must be called Main.java.
(in other IDEs, you can pick any name.)

7
Printing

Two ways to print a line of output on the console:


System.out.println() and System.out.print().

System.out.println() is just the way that you ask Java to


print out the value of something followed by a new line (ln).

System.out.print() without the ln will print out something


without advancing to the next new line. 

8
Find the errors.
pooblic class Errors
public static void main(String args){
System.out.print("Good morning! ")
system.out.print("Good afternoon!);
System.Print "And good evening!";

See next slide for all of the corrections.

9
Corrected!

public class Errors {


public static void main(String[] args){
System.out.print("Good morning! ");
System.out.print("Good afternoon!”);
System.out.print("And good evening!”);
}
}

10
Strings
• string: A sequence of characters to be printed.
– Starts and ends with a " quote " character.
• The quotes do not appear in the output.

– Examples: A string enclosed in quotes


is called a string literal.
"hello"
"This is a string. It's very long!"

• Restrictions:
– May not span multiple lines.
"This is not
a legal String."

– May not contain a " character.


"This is not a "legal" String either."
11
Using comments
• Where to place comments:
– at the top of each file (a "comment header")
– at the start of every method (seen later)
– to explain complex pieces of code

• Comments are useful for:


– Understanding larger, more complex programs.
– Multiple programmers working together, who must understand
each other's code.

12
Comments example
/* Alex Student, APCSA B2, Fall 2021
This program prints lyrics about the most viewed song. */

public class BabyShark {


public static void main(String[] args) {
// first verse
System.out.println(“Baby Shark, doo doo doo doo doo doo");
System.out.println(“Baby Shark");
System.out.println();

// second verse
System.out.println(“Mommy Shark, doo doo doo doo doo doo ");
System.out.println(“Mommy Shark");

// third verse
System.out.println(“Daddy Shark, doo doo doo doo doo doo ");
System.out.println(“Daddy Shark");

}
}
13
Indent Nicely!

public class Welcome{ public static void main(String[]


args){ System.out.println("Hi there!”
);System.out.println(”Welcome to APCS A!");}}

The code above will compile and run correctly. Java ignore whitespaces.
But it is very hard to read, please make an effort to indent nicely!

public class Welcome{


public static void main(String[] args){
System.out.println("Hi there!");
System.out.println(”Welcome to APCS A!");
}
}
14
Lab 1
Write a program that has the following outputs:

You must use exactly 5 different print statements.(println and/or


print).

Output:
I am Sam. Sam I am. I do not like them, Sam-I-am.
I do not like green eggs and ham.

15
Data Types
Data types can be categorized as either primitive or
reference.
The primitive data types used in this course define the set of
operations for numbers and Boolean(true or false) values.

Reference variables or object variables hold a reference(or


address) to an object of a class(more on this in a future lecture).
16
Primitive types
The primitive types on the AP Computer Science A exam are:

•int - which store integers (whole numbers like 3, -76, 20393)


•double - which store floating point numbers (decimal numbers
like 6.3, -0.9, and 60293.93032)
•boolean - which store Boolean values (either true or false).

17
Receipt example
What's bad about the following code?
public class Receipt {
public static void main(String[] args) {
// Calculate total owed, assuming 8% tax / 15% tip
System.out.println("Subtotal:");
System.out.println(38 + 40 + 30);
System.out.println("Tax:");
System.out.println((38 + 40 + 30) * .08);
System.out.println("Tip:");
System.out.println((38 + 40 + 30) * .15);
System.out.println("Total:");
System.out.println(38 + 40 + 30 +
(38 + 40 + 30) * .08 +
(38 + 40 + 30) * .15);
}
}
– The subtotal expression (38 + 40 + 30) is repeated
– So many println statements
– We will use variables to solve the above problems. 18
Variables

• variable: A piece of the computer's memory that is given a


name and type and can store a value.
– Like preset stations on a car stereo, or cell phone speed dial:

19
Declaration
• variable declaration: Sets aside memory for storing a value.
– Variables must be declared before they can be used.

• Syntax:
type name;
• The name is an identifier.

x
– int x;

– double myGPA; myGPA

20
Assignment
• assignment: Stores a value into a variable.
– The value can be an expression; the variable stores its result.

• Syntax:
name = expression;

x 3
– int x;
x = 3;

– double myGPA; myGPA 3.25


myGPA = 1.0 + 2.25;
21
Using variables
• Once given a value, a variable can be used in expressions:
string concatenation:
int x; string + number = concatenated string
(more on this later)
x = 3;
System.out.println("x is " + x); // x is 3
System.out.println(5 * x - 1); // 14

• You can assign a value more than once:


x 3
11
int x;
x = 3;
System.out.println(x + " here"); // 3 here

x = 4 + 7;
System.out.println("now x is " + x); // now x is 11

22
Declaration/initialization
• A variable can be declared/initialized in one statement.

• Syntax:
type name = value;

myGPA 3.95
– double myGPA = 3.95;

– int x = (12 - 3) * 2; x 18

23
Assignment and algebra
• Assignment uses = , but it is not an algebraic equation.

= means, "store the value at right in variable at left"

• The right side expression is evaluated first,


and then its result is stored in the variable at left.

• What happens here?


int x = 3; 3
x 5
x = x + 2;

24
Multiple Variables
• Multiple variables of the same type can be declared and
initialized at the same time.

• Syntax:

type name1, name 2, name3;


int x, y, z; // declare three integers.

type name1 = value1, name2 = value2, name3 = value3;


int a = 1, b = 2, c = 3; // declare and initialize
// three integers.

25
Assignment and types
• A variable can only store a value of its own type.
– int x = 2.5; // ERROR: incompatible types

• An int value can be stored in a double variable.


– The value is converted into the equivalent real number.

– double myGPA = 4; myGPA 4.0

26
Compiler errors
• Order matters.
– int x;
7 = x; // ERROR: should be x = 7;
• A variable can't be used until it is assigned a value.
– int x;
System.out.println(x); // ERROR: x has no value
• You may not declare the same variable twice.
– int x;
int x; // ERROR: x already exists

– int x = 3;
int x = 5; // ERROR: x already exists

• How can this code be fixed? 27


Printing a variable's value
• Use + to print a string and a variable's value on one line.
– double grade = (95.1 + 71.9 + 82.6) / 3.0;
System.out.println("Your grade was " + grade);

int students = 11 + 17 + 4 + 19 + 14;


System.out.println("There are " + students +
" students in the course.");

• Output:
Your grade was 83.2
There are 65 students in the course.

28
Receipt question
Improve the receipt program using variables.
public class Receipt {
public static void main(String[] args) {
// Calculate total owed, assuming 8% tax / 15% tip
System.out.println("Subtotal:");
System.out.println(38 + 40 + 30);
System.out.println("Tax:");
System.out.println((38 + 40 + 30) * .08);
System.out.println("Tip:");
System.out.println((38 + 40 + 30) * .15);
System.out.println("Total:");
System.out.println(38 + 40 + 30 +
(38 + 40 + 30) * .15 +
(38 + 40 + 30) * .08);
}
}

29
Receipt answer
public class Receipt {
public static void main(String[] args) {
// Calculate total owed, assuming 8% tax / 15% tip
int subtotal = 38 + 40 + 30;
double tax = subtotal * .08;
double tip = subtotal * .15;
double total = subtotal + tax + tip;

System.out.println("Subtotal: " + subtotal);


System.out.println("Tax: " + tax);
System.out.println("Tip: " + tip);
System.out.println("Total: " + total);
}
}

30
Bell Work
• Make a TempConverter class that calculates the temperature
and gives the following output:
Celsius Temperature: 24
Fahrenheit Equivalent: 75.2

You must use variables for


• base = 32
• conversionFactor = 9.0/5.0

Also have variables to store Celsius temperature and Fahrenheit


temperature

31
Task
• Revise the TempConverter class so that it will take a user input
to give the converted temperature in Fahrenheit!

32
Task
• Revise the TempConverter class so that it will take a user input
to give the converted temperature in Fahrenheit!

33
Type boolean
• boolean: A logical type whose values are true and false.

int age = 22;


boolean minor = (age < 21);
boolean lovesAPCS = true;
System.out.println(minor); // false
System.out.println(lovesAPCS); // true

34
final
• The keyword final can be used in front of a variable
declaration to make it a constant that cannot be changed.
Constants are traditionally capitalized.

public class TestFinal


{
public static void main(String[] args)
{
final double PI = 3.14;
System.out.println(PI);
PI = 4.2; // This will cause a syntax error
}
}

35
Naming variables
The name of the variable should describe the data it holds. A name
like score helps make your code easier to read.

A name like x is not a good variable name in programming, because it gives


no clues as to what kind of data it holds.

Do not name your variables crazy things like thisIsAReallyLongName,


especially on the AP exam. You want to make your code easy to understand,
not harder.

36
Naming variables
The convention in Java and many programming languages is to always start a
variable name with a lower case letter and then uppercase the first letter of
each additional word.

Variable names can not include spaces so uppercasing the first letter of
each additional word makes it easier to read the name. Uppercasing the first
letter of each additional word is called camel case.

int numOfLives = 3; // camel case to highlight words

Another option is to use underscore symbol _ to separate words, but you


cannot have spaces in a variable name. Java is case sensitive
so playerScore and playerscore are not the same.

int num_of_lives = 3; // use _ to highlight words.


37
Keywords
• keyword: An identifier that you cannot use to name a variable
because it already has a reserved meaning in Java.
abstract default if private this
boolean do implements protected throw
break double import public throws
byte else instanceof return transient
case extends int short try
catch final interface static void
char finally long strictfp volatile
class float native super while
const for new switch
continue goto package synchronized

38
Input and System.in

• interactive program: Reads input from the console.


– While the program runs, it asks the user to type input.
– The input typed by the user is stored in variables in the code.

– Can be tricky; users are unpredictable and misbehave.


– But interactive programs have more interesting behavior.

• Scanner: An object that can read input from many sources.

– Communicates with System.in (the opposite of System.out)


– Can also read from files, web sites, databases, ...

39
Scanner syntax

• The Scanner class is found in the java.util package.


import java.util.Scanner; // so you can use *

• Constructing a Scanner object to read console input:


Scanner name = new Scanner(System.in);

– Example:
Scanner input = new Scanner(System.in);

40
Scanner methods

Method Description
nextInt() reads an int from the user and returns it
nextDouble() reads a double from the user
next() reads a one-word String from the user
nextLine() reads a one-line String from the user

– Each method waits until the user presses Enter.


– The value typed by the user is returned.

System.out.print("How old are you? "); // prompt


int age = input.nextInt();
System.out.println("You typed " + age);

• prompt: A message telling the user what input to type.


41
Scanner example
import java.util.Scanner; // so that I can use Scanner
public class UserInputExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("How old are you? "); age 29


int age = input.nextInt();
years 36
int years = 65 - age;
System.out.println(years + " years to retirement!");
}
}

• Console (user input underlined):


29
How old are you?
36 years until retirement!
42
Scanner example 2
import java.util.Scanner; // so that I can use Scanner
public class ScannerMultiply {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please type two numbers: ");
int num1 = input.nextInt();
int num2 = input.nextInt();
int product = num1 * num2;
System.out.println("The product is " + product);
}
}

• Valid Outputs (user input underlined):

Please type two numbers: 8 6 Please type two numbers: 8


6
The product is 48 The product is 48
// 2 tokens separated by new
// 2 tokens separated by space // line 43
Unit 1: Primitive Types
Using Escape Sequences

Adapted from:
1) Building Java Programs: A Back to Basics Approach
by Stuart Reges and Marty Stepp
2) Runestone CSAwesome Curriculum
This work is licensed under the
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

https://longbaonguyen.github.io
Escape Sequence
• / : forward slash (imagine someone leaning forward)
• : backward slash (think someone leaning back)

45
Bell Work Activity
• Select one or two articles from the following website:
– https://technews.acm.org/
– After 5 minutes, share among table:
• “What was the most interesting part of your article?”

• After today’s worksheet work on Unit 9.6 and 9.7

46
Bell Work Question
Using what we’ve learned with the Scanner Class, create a program
that ask the user:
–“How many hours did you sleep today?”
–Allow the user to enter a number
–If the student enters 7 or more, then tell the user:
slept well: true
–Or if less than 7, then:
slept well: false
Hint: Use boolean to test true or false

47
Bell Work Question
• What do the following expressions equal to?

1 - 2 - 3 -4 or 0
1 + 3 * 4 16 or 13

6 + 8 / 2 * 3 18 or 7.333333333333333333

(1 + 3) * 4

1+3 * 4-2

48
Unit 1: Primitive Types
Arithmetic Operations

Adapted from:
1) Building Java Programs: A Back to Basics Approach
by Stuart Reges and Marty Stepp
2) Runestone CSAwesome Curriculum
This work is licensed under the
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

https://longbaonguyen.github.io
Arithmetic operators
• expression: A value or operation that computes a value.

• Examples: 1 + 4 * 5
(7 + 2) * 6 / 3
• operator: Combines multiple values or expressions.
– + addition
– - subtraction (or negation)
– * multiplication
– / division
– % modulus (a.k.a. remainder)

• As a program runs, its expressions are evaluated.


– 1 + 1 evaluates to 2
– System.out.println(3 * 4); prints 12
• How would we print the text 3 * 4 ?

50
Integer division with /
• When we divide integers, the remainder is excluded.
– 14 / 4 is 3, not 3.5
– What would 45 / 10 give us how about 10/3

• More examples:
– 32 / 5 is 6
– 84 / 10 is 8
– 156 / 100 is 1

– Dividing by 0 causes an error when your program runs. This error


is also called an ArithmeticException.

51
Integer remainder with %
• The % operator computes the remainder from integer division.
– 14 % 4 is 2
– 218 % 5 is 3
3 43
4 ) 14 5 ) 218
12 20
2 18
15
3

• Applications of % operator:
– Obtain last digit of a number: 230857 % 10 is 7
– Obtain last 4 digits: 658236489 % 10000 is 6489
– See whether a number is odd: 7 % 2 is 1, 42 % 2 is 0

52
% Example
public static void main(String[] args){
System.out.println(45 % 6);
System.out.println(2 % 2);
System.out.println(8 % 10);
System.out.println(11 % 0);
System.out.println(-21 % 4); // probably not on AP
System.out.println(21 % -4); // probably not on AP
}
Output:
3
0
8
ArithmeticException
-1
1
53
Precedence
• precedence: Order in which operators are evaluated.
– Generally operators evaluate left-to-right.
1 - 2 - 3 is (1 - 2) - 3 which is -4

– But * / % have a higher level of precedence than + -


1 + 3 * 4 is 13
6 + 8 / 2 * 3
6 + 4 * 3
6 + 12 is 18

– Parentheses can force a certain order of evaluation:


(1 + 3) * 4 is 16

– Spacing does not affect order of evaluation


1+3 * 4-2 is 11
54
Even or Odd
An important use of the % operator is to test for divisibility.
For example, is a number even or odd?
Or is a number a multiple of 3?

// a number is even if it has no remainder


// when divided by 2.
if(number % 2 == 0){

}
// multiple of 3
if(number % 3 == 0){

}
55
Expressions
Find the exact change for 137 cents using quarters, dimes,
nickels and cents. Use the least number of coins.

How many quarters? 137 / 25 = 5 quarters (Integer Division!)

What’s leftover? 137 % 25 = 12 cents

How many dimes? 12 / 10 = 1 dime

What’s leftover? 12 % 10 = 2 cents

How many nickels? 2 / 5 = 0 nickels.

What’s leftover? 2 % 5 = 2 cents.

How many pennies? 2 / 1 = 2 pennies


56
Number Formatting
Ways to format your number to display a rounded number to a specific
place value

public class MyClass {


public static void main(String args[]) {
double price = 3.5;
int volume = 12;
int packVolume = 6*12;

double totPrice = price/packVolume;

System.out.println(Math.round(totPrice*100)/100.0);
System.out.printf("%f", totPrice);
}
}

57
Computation Lab:

Problem Statement
Suppose you are asked to write a program that simulates a vending machine. A customer selects
an item for purchase and inserts a bill into the vending machine. The vending machine
dispenses the purchased item and gives change. We will assume that all item prices are
multiples of 25 cents, and the machine gives all change in dollar coins and quarters. Your task is
to compute how many coins of each type to return.
Declare variables pennies, dollars, and cents

If you’re done, could you also add dime, nickels, and pennies to return to user if the item
price was 212 cents.

58
Check with neighbor
•1 * 2 + 3 * 5 % 4  1 + 8 % 3 * 2 - 9
• \_/  \_/
| |
2 + 3 * 5 % 4 1 + 2 * 2 - 9
• \_/  \___/
| |
2 + 15 % 4 1 + 4 - 9
• \___/  \______/
| |
2 + 3 5 - 9
• \________/
 \_________/
| |
5 -4

59
How about with Real
number
• 2.0 * 2.4 + 2.25 * 4.0 / 2.0
• \___/
|
4.8 + 2.25 * 4.0 / 2.0
• \___/
|
4.8 + 9.0 / 2.0
• \_____/
|
4.8 + 4.5
• \____________/
|
9.3

60
Mixing types
• When int and double are mixed, the result is a double.
– 4.2 * 3 is 12.6

• The conversion is per-operator, affecting only its operands.


• 2.0 + 10 / 3 * 2.5 - 6 / 4
– 7 / 3 * 1.2 + 3 / 2
• \___/
– \_/ |
| 2.0 + 3 * 2.5 - 6 / 4
2 * 1.2 + 3 / 2 • \_____/
– \___/ |
| 2.0 + 7.5 - 6 / 4
2.4 + 3 / 2 • \_/
– \_/ |
2.0 + 7.5 - 1
| • \_________/
2.4 + 1 |
– \________/ 9.5 - 1
| • \______________/
3.4 |
8.5
61
Question?
● What will the following output give?

public class Test{


public static void main(String[] args){
System.out.println(1 / 3);
System.out.println(1.0 / 3);
System.out.println(1 / 3.0);
System.out.println((double) 1 / 3);
}
}

0
0.3333333333333333
0.3333333333333333
0.3333333333333333
1.5 Casting and Ranges of Variables
What is Casting?

● Involves lost of information when


converting decimal to integer type
● 4 Bytes can hold how much?
Primitive Data Types (8)

● Integer (4) ● Char


○ Byte 8 bits
○ Char 2 bytes
○ Short 2 bytes ● Boolean
○ Int 4 bytes ○ Boolean true or false
○ Long 8 bytes

● Floating (2)
○ Float 4 bytes *These data types do not need to be
represented using objects
○ Double 8 bytes
Type casting
• type cast: A conversion from one type to another.
– To promote an int into a double to get exact division from /
– To truncate a double from a real number to an integer

• Syntax:
(type) expression

Examples:
double result = (double) 19 / 5; // 3.8
int result2 = (int) result; // 3

66
More about type casting
• Type casting has high precedence and only casts the item
immediately next to it.
– double x = (double) 1 + 1 / 2; // 1.0
– double y = 1 + (double) 1 / 2; // 1.5

• You can use parentheses to force evaluation order.


– double average = (double) (a + b + c) / 3;
– The code above cast the sum (a+b+c) into a double.

• A conversion to double can be achieved in other ways.


– double average = 1.0 * (a + b + c) / 3;

67
Casting Example
public static void main(String[] args){
double x = 4 / 3;
double y = (double)(125/10);
double z = (double) 28 / 5;
System.out.println(x + “ ” + y + “ ” + z);
}

Output:
1.0 12.0 5.6

68
Round to the nearest integer
• casting can be used to round a number to its nearest integer.

double number = 8.0 / 3;


// round a positive number to its nearest integer
int nearestInt = (int)(number + 0.5);
double negNumber = -19.0 / 3;
// round a negative number to its nearest integer
int nearestNegInt = (int)(negNumber – 0.5);

What is the value of nearestInt and nearestNegInt?


Answer: 3 and -6

69
1.4 Compound Assignment Operators

+=

-=

*=

/=

%=

++

--
Increment and decrement
shortcuts to increase or decrease a variable's value by 1

Shorthand Equivalent longer version


variable++; variable = variable + 1;
variable--; variable = variable - 1;

int x = 2;
x++; // x = x + 1;
// x now stores 3
double gpa = 2.5;
gpa--; // gpa = gpa - 1;
// gpa now stores 1.5

71
Modify-and-assign
shortcuts to modify a variable's value

Shorthand Equivalent longer version


variable += value; variable = variable + value;
variable -= value; variable = variable - value;
variable *= value; variable = variable * value;
variable /= value; variable = variable / value;
variable %= value; variable = variable % value;

x += 3; // x = x + 3;
gpa -= 0.5;
// gpa = gpa – 0.5;
number *= 2;
// number = number * 2;

72
Code Tracing
What are the values of x, y and z after tracing through the
following code?

int x = 0;
int y = 5;
int z = 1;
x++;
y -= 3;
z = x + z;
x = y * z;
y %= 2;
z--;
Answer: x = 4, y = 0, z = 1

73
Practice
Practice
Practice
Practice
Write a program that can determine whether a user input value
is even or odd. It should out even if the number the user typed
in was even or output odd if it was not even.
Hint: what variable type do you need, what statement can you
use?

77
Lab 1

78
Lab 1

For example, if the list is {78,80,77}.

Average =78.33333333333333

Variance = 1.5555555555555556
Standard deviation = 1.247219128924647

79
Lab 1
Create a class and follow the comments below to write a program that compute
some statistics.

public class Statistics


{
public static void main(String[] args)
{
// 1. Declare 3 int variables for grades and initialize them to 3 values
// 2. Declare an int variable for the sum of the grades
// 3. Declare a double variable for the average of the grades
// 4. Write a formula to calculate the sum of the 3 grades
// 5. Write a formula to calculate the average of the 3 grades from the //
sum using division and type casting.
// 6. Print out the average
// 7. Declare a double variable and calculate the variance
// 8. Declare a double variable to compute the standard deviation.
// 9. Print out the variance and standard deviation.
}
}
80
Lab 2
Use the following template(or something similar) to write a program that
gives exact change with the least number of coins for a given number of
cents. Use intermediate variables to help your calculation.

public static void main(String[] args){


int totalCents = 137; //137 can be any number
…..
// your code here.

Output: 5 quarters, 1 dimes, 0 nickels, 2 pennies.

81

You might also like