Topic: Name: _____________________________________________________ Period: _______ Date: _______________________ Lab03: Variables.

advertisement
Topic:
Lab03: Variables.
Objectives
Name: _____________________________________________________
Period: _______ Date: _______________________



I will be able to define and initialize a variable.
I will be able to use variables in equations
I will be able to display a variable using System.out.print () or println()
What are the common types
of variables?
Integer : whole number, both positive and negative. Ex: -6, 0, 8432
Double: decimal number. Ex: -2.89, 4.3289, 5.0
Strings: collection of characters Ex: “I will learn how to program in Java”
Boolean: true or false
What type of variable would
you use?
Your Name:
Your age:
Amount of Loan:
Interest rate on your loan:
Number of payments before it’s paid off:
Your monthly payment:
What are the Java keywords
used to define variables:
Integer : int
Double: double
Strings: String
Boolean: boolean
HOW DO I:
declare and initialize
variables?
int numBurgers = 6;
double costOfBurgers = 4.25;
String burgerString = “PVHS Big Burger”;
use variables in a equation?
double burgerCost = numBurgers * costBurgers;
apply a 10% discount?
burgerCost = burgerCost * .90;
burgerCost = burgerCost – burgerCost*.1;
increment a variable?
numBurgers = numBurgers + 1;
decrement a variable?
numBurgers = numBurgers – 1;
Applying variables to the Climber class
What are the components of a variables: state
methods: verbs
class?
- Constructors: special methods used to initialize the state of an object when first
created
- Instance methods: turnRight(), move(), pickBeeper()
In the Climber class, how do I
declare variables?
- Before the constructors
public
{
int
int
int
int
class Climber extends Athlete
upRightCalls=0;
upLeftCalls=0;
downRightCalls=0;
downLeftCalls=0;
public Climber(int x) { .. }
How do I increment the
variables?
public void climbUpRight()
{
upRightCalls = upRightCalls + 1;
}
How do I display the
variables?
public void printCounts ()
{
System.out.println(" upRightCalls=" + upRightCalls);
System.out.println(" upLeftCalls=" + upLeftCalls);
System.out.println(" downRightCalls=" + downRightCalls);
System.out.println(" downLeftCalls=" + downLeftCalls);
}
How do you input data from
the keyboard?
Example:
class: Scanner
methods:
nextInt() – read an Integer
nextDouble() – read a Double
next() – read a String
import java.util.Scanner;
in main():
//create a new Scanner object,reads data from keyboard
Scanner input = new Scanner (System.in);
System.out.println(“Enter number of Burgers: “);
int numBurgers = input.nextInt();
double costBurgers = numBurgers * COST_BURGER;
System.out.println("Cost Burgers = $" + costBurgers);
double total = costBurgers; // + costFries + costCokes;
//add a 15% tip
total = total + total * .15;
Summary:
Download