Transcript week6

APCS-A: Java
Data Conversion & Input/Output
October 11, 2005
week6
1
Review
• Java Quiz
• Calculator/Graphics Homework
• Last Week’s Lectures:
 Scope
 Data Types
week6
2
Converting Data Types
• What do we do if we want to add an int variable
to a double variable?
 Or do int / double where we want an int answer? A
double answer?
 Or we want to do int / int but want a double
answer
• There are three ways that Java deals with this
 Assignment conversion
 Promotion
 Casting
week6
3
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
double a = 5/2;
 Do you think a will hold 2.0 or 2.5?
week6
4
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
double x = 5.0/2; //promotes 2 -> 2.0 first
• 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
int z = 43;
System.out.println(“z
week6
is” + z);
5
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:
double answer = (double) x / y;
OR
week6
double answer = x / (double) y;
The other variable gets
promoted automatically
6
You Try
• Data Conversion Exercises:
 Declare some variables:
int iResult, num1 = 25, num2=34, num3=-1;
double dResult, v1=3.4, v2=45.34, v3=55.44;
 Try some calculations and see what happens (print
the results to see what you get):
iResult
dResult
iResult
dResult
dResult
iResult
week6
=
=
=
=
=
=
num1/num2; dResult = num1/num2;
v1/num1;
v1/v2;
dResult = v1/v2;
(double) num1/num3;
(int) (val1/num3);
(int) (val1/num3);
7
Input & Output
• We’ve already done basic output - printing to the
terminal window
System.out.print(“Hello”);
System.out.println(“ Hello”);
• Let’s look at how to better format the output and
how to print some special characters
week6
8
Printing Variables
• In lab last week, we saw that we could
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)
 Although we will have to do something special if we
want an object to print something meaningful - by
default printing an object will just give us the memory
address of the object
week6
9
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 thing following has some special
meaning
week6
10
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 (with the new operator):
Scanner sc = new Scanner(System.in);
• Then use that object by calling its methods:
week6
int i = sc.nextInt();
11
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
12
APCS-A: Java
Input/Output Continued
October 12, 2005
week6
13
Review
• Yesterday we talked about output and using the
Scanner class
• Did we all get input from the user?
week6
14
Getting Input
• Import Class from the library
import java.util.Scanner;
• Create an object to use it (with the new operator):
Scanner sc = new Scanner(System.in);
• Use object by calling its methods
int i = sc.nextInt();
String s = sc.nextLine();
week6
15
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
16
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: “);
“ + x);
a word followed by enter:
“ + s);
17
If Statements
• Do you remember how we handled conditionals in Alice?
• If statements have a similar syntax and usage in Java
if (<< conditional >> ) {
<< body >>
}
else {
<< body >>
}
week6
18
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
19
Lab / Homework
• Menu Lab: Make a expandable menu class that
can be used to run the calculator program
week6
20
APCS-A: Java
Constructors
October 13, 2005
week6
21
Review
• 80 point Quiz
• Talk about some concepts that were raised
during the lab yesterday
 We will revisit the Menu Code after lecture and
fix it up
week6
22
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
23
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
24
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
25
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
26
Objects as Data Types
• We’ve created a Dog object…
• 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
27
The Dot Operator
• A Dog remote control would have buttons
to do something (to invoke the dog’s
methods)
Eat
Bark
d2.bark();
DOG
Think of the dot operator like pushing a
button on a remote control
week6
Imagine this is a
Remote control
28
Interacting Classes
• So in class yesterday we said that the Calculator class
had a Menu object
 Now we see better how these classes interact
 The Calculator creates the Menu object and then has a pointer to
the Menu so that it can call the Menu’s public methods
• The strength of this approach is that the Menu is
separate from the Calculator
 So that the Menu can be used by other objects as well
 We can’t really do this with our current implementation because
we hard-coded the menu items in the Menu class
• In the future, we will make Menu more generic so that we can use it
in other situations
week6
29
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
30
Menu Lab
• Menu:




private void printMenu()
private int askForInput()
private int checkChoice(int num)
public int run()
• Calculator:
 private void doUserChoice(int choice)
 public void runUserInterface()
week6
31
APCS-A: Java
Java API & Strings
October 14, 2005
week6
32
Review
• 80 point Quiz
 A little disappointing -- make sure that you
review your notes and that you understand the
lectures and code we see in class each day
• Menu Code - Is it working for everyone?
 Do we understand everything up to this point?
week6
33
Java API
• API = application programming interface
• In Java, it is the list of all the classes available,
•
with details about the constructors, methods, and
usually a description of how to use the class
I had you download the full API to your
computers at home, there is also a scaled down
version that only has the methods and classes
that are used for the APCS test
 That is available online at:
http://www.cs.duke.edu/csed/ap/subset/doc/
week6
34
Why this is Cool
• There is so much code in Java that is
already written for you - you just have to
 Know that it is out there
 Figure out how to use it
• The API gives a standard way to look at
classes and methods so that any Java
programmer can understand how to use a
class without having to see the code
week6
35
String Class (APCS subset)
week6
36
Strings are immutable
• Once a string is created, it cannot change
• So string methods always return new
strings -- that way you can just change the
pointer
String name = “Jane”;
X
“Jane”
String name
name = name + “ Dow”;
week6
“Jane Dow”
37
Other String Methods
(Java API)
• In addition to what the AP people think you
need to know, there are some other cool
String methods








week6
boolean equalsIgnoreCase(String str)
String replace (char oldChar, char newChar)
boolean endsWith (String suffix)
boolean startsWith (String prefix)
String toUpperCase()
String toLowerCase()
String concat(String str)
String trim() //takes off white space from front &
back
38
Lab/Homework
• Write a program that will generate somebody’s StarWars
Name
 Input: First Name, Last Name, Mom’s Maiden Name, City of Birth
 Calculate the Star Wars Name:
• For the new first name:
 1. Take the first 3 letters of 1st name & add
 2. the first 2 letters of last name
• For the new last name:
 3. Then take the first 2 letters of Mom's maiden name & add
 4. the first 3 letters of the city person was born.
week6
39