Transcript Slide 1

APCS-AB: Java
Data Types, Returns, Scope
October 11, 2005
week6
1
Review
• (Turn in Abstracts & Mid-Quarter comments)
• How did rest of the lab go?
• Last Thursday we talked about:






Syntax
Concatenation
Variables
Assignment Statements
Constants
Naming practices (I expect you to follow the Java
conventions)
 Arithmetic Operators
week6
2
Variables
• The burning question: What can I name my variables?
 Almost anything… But not Java reserved words…
 abstract do if package synchronized boolean
double implements private this break else import
protected throw byte extends instanceof public
throws case false int return transient catch
final interface short true char finally long
static try class float native strictfp void
const for new super volatile continue goto null
switch while default
• Luckily, BlueJ colors these words a different color so you
will know there is something special about them before
you know what they all mean
week6
3
Data Types
• A variable's data type determines the values that the
variable can contain and the operations that can be
performed on it
• Primitive Data Types are built-in data types (in Java,
there are 8 of them)
 boolean, char, byte, short, int, long, float, double
week6
Type
Storage
Min Value
Max Value
boolean
1 bit
0 (false)
1 (true)
byte
8 bits
-128
128
int
32 bits
-2,147,483,648
2,147,483,647
double
64 bits
Approx -1.7E+308 with Approx 1.7E+308 with
15 significant digits
15 significant digits
4
Pre-Defined Data Types
• Pre-defined data types are just objects that Java
has provided you that store information
 Like a String
• Stores a section of text
• Always in double quotes
• Java has several other data structures to store
data in useful ways
 We will be learning many of them this semester and
next
week6
5
Converting Data Types
• What do we do if we want to compare an int
variable to a double variable?
 Or do int + double?
 int / double?
• There are three ways that Java deals with this
 Assignment conversion
 Promotion
 Casting
week6
6
Assignment Conversion
• Occurs when one type is assigned to a variable
of another type during which the value is
converted to the new type (only widening
conversions can happen this way)
double dollars = 5;
• Here the 5 will get automatically converted to a
double (5.0) to be stored in the variable dollars
week6
7
Promotion
• If we divide a floating point number (float or
double) by an int, then the int will be
promoted to a floating point number before
the division takes place
• When we concatenate a number with a
string, promotion also happen - the number
is converted (promoted) to a string, and
then the strings are joined
week6
8
Casting
• The most general form of conversion in Java
 If a conversion is possible, you can make it happen with casting
• You cast a variable by automatically applying a data type
to it
int x = 5;
double dollars = 5.234;
x = (int) dollars; //forces the double to become an int
• This will truncate (not round) the original value
• This can also be used to make sure we get the answer
we expect --> if we want to divide 5/2 and get 2.5, then
we want to force the result to be a double:
week6
double answer = (double) x / y;
OR
double answer = (double) x / (double) y;
9
Topics in Methods
public String myMethod(int x){
String s = “Hello” + x;
return s;
}
• What happens with the return statements?
• Where does the variable s live? (What is
its scope?)
week6
10
Return Statements
• In Scheme, everything we programmed was a
function that was evaluated
 The functions we wrote always returned a value that’s how everything was defined
• In Java, you can write methods that act the same
way
 Return type can be any primitive or object data type
• Or you can also write methods that simply
perform a set of statements without returning a
value
 void methods
week6
11
Return Statements
public void add (int x, int y) {
int z = x+y;
System.out.println(“answer is: “ + z);
}
public int add (int x, int y) {
return (x+y);
}
The first function is called with the statement:
add(5, 10);
The second statement can be called in many ways, but we
probably want to do something with the answer returned
week6
12
Using return values
public int add(int x, int y)
• In BlueJ, we could just get the answer back
in an method result window
• Or we could use the answer in another part
of our program
 In another method
 In a statement or some sort (assignment
statement, print statement, etc)
System.out.println(“answer is: “ + add(5,10));
int answer = add(5, 10); //notice I “catch” the value in an int variable
divide(answer, 2); // could have also done: divide(add(5, 10), 2)
week6
13
Scope
• Parameters and variables have scope
 This means that they are only valid in the block (between the
curly braces) in which they were defined
• Class scope
 Variables defined at the top of the program (not inside any
constructors or methods) -- these variables can be used
anywhere in the class
• Constructor/Method scope
 parameters passed in to a constructor/method can only be
referred to in that constructor/method
 Variables declared in a method can only be referred to in that
method
• What happens when you refer to a parameter/variable
outside the block it was defined in?
week6
14
Scope
public class ScopeClass {
int x = -1;
String s = “gook ”;
public void scopeFunc1() {
String s = “Gobble-D ”;
Question #1
System.out.println(s + x);
scopeFunc2(42);
}
public void scopeFunc2(int x) {
Question #2
System.out.println(s+x);
}
1) What do you get if you make a call to scopeFunc1()?
}
2) What do you get if you make a call directly to scopeFunc2()?
week6
15
Why does scope matter?
• In the last example, s wasn’t even a particularly good
•
variable name… so we could have come up with even
more descriptive names and not had the problem of
trying to refer to two different variables with the same
name
But what if we were trying to model a Car class:
 We could have had an instance variable: String color, for the
Car’s color
 We could have defined a paint method: public void paint
(String color) {} in which we wanted to reset the Car’s
color (the instance variable) to the new color (passed in as a
parameter to the method)
week6
16
How do we solve this
scope problem?
• The novice way -- name your parameters something
different than your class (instance) variables
 In Car class, we could have the instance variable, String
color
 In the paint method, we could instead call the parameter String
newColor
• The expert way -- keep the names the same, but know
that if you want to refer to the instance variable, you need
to further identify the variable:
 the this keyword refers to the object itself
 this.color = color;
week6
17
Homework
• Write a calculator class to operate on integers
and doubles
 Have it have methods for add, subtract, multiply,
divide, and remainder
 Write a method that will return the average of 3
numbers
 Write a method that will determine the value of coins
in a “jar” and print the total in dollars and cents. The
method will take in 4 integer parameters, representing
the numbers of each kind of coin
week6
18
APCS-AB: Java
Constructors & Lab
October 12, 2005
week6
19
Review
• (LAST CHANCE - Turn in Abstracts & Mid-Quarter
comments)
• Calculator Homework
• Methods for add, subtract, multiply, divide, and remainder
• Write a method that will return the average of 3 numbers
• Write a method that will determine the value of coins in a “jar” and
print the total in dollars and cents. The method will take in 4 integer
parameters, representing the numbers of each kind of coin
week6
20
Constructors
• The constructor is a special kind of public method - it has
the same name as the class and no return type
 Constructors are used to set initial or default values for an
object’s instance variables
public class Dog{
String name;
String breed;
public Dog(String name, String dogBreed){
this.name = name;
breed = dogBreed;
}
}
week6
21
Default Constructor
• All Java classes have a default constructor
to create an object
Student s = new Student();
• Would call the default Student constructor,
which just makes the object (what we’ve
already been doing in BlueJ)
• Once we define another constructor (like
we did for Dog), the default constructor is
no longer available
week6
22
Making Objects
• So now when we construct an object, we can pass in
initial values:
Dog d = new Dog(“Fido”, “bulldog”);
Dog d2 = new Dog(“Spot”, “retriever”);
• This code will create two Dog objects, calling the
constructor to set the name and the breed for each object
week6
23
Multiple Constructors
• You can define multiple constructors for an object
public class SportsTeam{
int ranking;
String name;
public SportsTeam(String teamname){
name = teamname;
ranking = 0;
}
public SportsTeam (int ranking, String s){
this.ranking = ranking;
name = s;
}
}
• Why would you want to do this?
week6
24
Lab
• Design classes in Java that will model a simple Fantasy Football league
 One class will be the “League”
 The second class will be an individual “Team”
 The third class will be an individual “Player”
• For each class, think about:
 What attributes each of them will have (instance variables)?
 What each of the objects can do (methods)?
• What your work should look like:
 For each class, code the class into BlueJ using proper syntax and naming
conventions
 For variables, put the declarations in the classes and provide comments for each,
and the values should be set in the constructor
 For methods, put the declarations in the classes, provide comments for each, and
have each method print the “action” that it will do
• Each class must have at least two variables and methods identified
week6
25
APCS-AB: Java
Input/Output & Debugging
October 13, 2005
week6
26
Review
• Fantasy Football Design
 Player
 Team
 League
• 80 point quiz
week6
27
Designing a Class
• Identify what kinds of data is appropriate for your class -these are the instance variables
 Data Type and Name
• Think about the actions that are appropriate for that class
-- these are the methods
 Does that action return anything?
 Does that action require any additional data?
• If so, what is an appropriate name and data type for that parameter?
 Finally what does the method actually need to do
• For many modeling assignments, we start with a print statement
here and later will code in the actual functionality
week6
28
Objects as Data Types
• Object data types are not the same as
primitive data types
 They are references to the object, instead of
containers holding the object
 A reference is like a pointer or an address of
an object
• A good way to think of this object reference
is as a remote control
week6
29
The Dot Operator
• A Dog remote control would have buttons
to do something (to invoke the dog’s
methods)
Eat
Bark
Dog myDog = new Dog();
myDog.bark();
DOG
Think of the dot operator like pushing a
button on a remote control
week6
Imagine this is a
Remote control
30
Objects starting other objects
• Objects can create other objects
Car c = new Car(“BMW”);
• And then call any of the public methods of
that object
c.getLicensePlate();
week6
31
Input & Output
• We’ve already done basic output - printing to the terminal
window
• Let’s look at how to better format the output and how to
print some special characters
week6
32
Printing Variables
• We can print the values of variables
System.out.println(“The value of x is: “ + x);
• And this would work for x of any data type (so it
doesn’t matter if x is a primitive data type or a
String or any other kind of object)
 But as we saw yesterday, if we want a programmerdefined object to print nicely, we need to provide the
following method in the classes we define:
public String toString() { }
week6
33
Print Statement Debugging
• Often programmers want to check the
status of a program at a given point during
development
• Simple print statement in key locations can
help figure out what is happening with the
code
 They can be a great problem-solving strategy
week6
34
Output
• We often want to format the output in special ways to make it look
better:




To print a new line: \n
To print a tab: \t
To print a quotation mark in the output: \”
To print a slash in the output: \\
• All of these “codes” go inside the string literal that is being printed:
System.out.println(“\n \t \” Hello \” ”);
• The \ is the escape character for the compiler - it indicates that the
symbol following has some special meaning
week6
35
Input
• Java 1.5 has a new class called Scanner that makes it
•
much easier to get input from the terminal
To make the class available in your code, you must
import it from the library:
import java.util.Scanner;
• Since it is a class, we must create an object to use it and
tell it where it is getting the input from, for now from the
terminal window (System.in)
Scanner sc = new Scanner(System.in);
• Then use that object by calling its methods:
int i = sc.nextInt();
week6
36
Scanner Methods
• The Scanner class will split up input into tokens (by using white
space delimiters)
• The Scanner Class has many methods, but the ones you will care
about right now are:
 nextLine() --> gets a String, stopping when the user hits return
 nextInt()
 nextDouble()
• Note: right now, this will only work if the user follows your instructions
and inputs the right kind of data for you -- we will learn how to make
the code more robust later
week6
37
Asking for Input
• Since we just said that the user will have to enter
data carefully at first, we want our output
instructions to be clear:
System.out.println(“Please enter
int x = sc.nextInt();
System.out.println(“You entered:
System.out.println(“Please enter
String s = sc.next();
System.out.println(“You entered:
week6
a whole number: \n>“);
“ + x);
a word followed by enter: \n>“);
“ + s);
38
APCS-AB: Java
Input/Output & Random
October 14, 2005
week6
39
Review
• Scanner Class
week6
40
Scanner Methods
• The Scanner class will split up input into tokens (by using white
space delimiters)
• The Scanner Class has many methods, but the ones you will care
about right now are:
 nextLine() --> gets a String, stopping when the user hits return
 nextInt()
 nextDouble()
• Note: right now, this will only work if the user follows your instructions
and inputs the right kind of data for you -- we will learn how to make
the code more robust later
week6
41
Asking for Input
• Since we just said that the user will have to enter data carefully at
first, we want our output instructions to be clear:
• Example Program:
import java.util.Scanner;
public class Example{
Scanner sc = new Scanner(System.in);
public void run(){
System.out.println(“Please type your name: \n>“);
String s = sc.next();
System.out.println(“Hello “ + s);
}
}
week6
42
If Statements
• If statements have the following syntax and usage in Java:
if ( << conditional >> ) {
<< body >>
}
else {
<< body >>
}
• The << conditional >> can be any true or false conditional




week6
A simple boolean like (true)
A check for equality like (x == 5)
A greater than or equal to like (x >= 1)
A combination of the above with &&(and) , ||(or), or another conditional
(( x==5 && y == 2) || (z > 42))
43
Nesting if/else Statements
• In Java, you can also treat if statement blocks as a single
statement
 So you can nest multiple if statements inside one another like :
if ( << conditional >> ) {
<< body >>
}
else if ( << conditional >> ) {
<< body >>
}
else {
<< body >>
}
week6
44
Introduction to Commenting
Code
• Comments before signature of methods
 To tell what the method does
• Comments for variables
 To explain what the variable holds, what they are used for
• Comments within methods
 To explain what is going on; used when it is not immediately clear
from looking at the code
• Also, this allows me to see what you are trying to do,
even if your code doesn’t work!
 Make the comments be pseudocode if you can’t get your code to
work!
week6
45
Menu Lab
• In this lab, we are going to make a Menu
object that will be responsible for printing a
menu of options, getting user input, and
verifying that the user input is valid
week6
46
Random Class
• Package: java.util.Random;
• Pseudo-random number generator
 A program can never be completely random, so this
class does the best it can, it produces a random
number based on an initial “seed” value (the current
time in milliseconds)
• Three methods of interest:
 int nextInt(int n) //number between 0 and n-1
 int nextInt() //any possible int value
 double nextDouble() //number [0.0 … 1.0)
week6
47
Weekend Homework
• Finish Menu Lab
week6
48