39
week6 1 APCS-A: Java Data Conversion & Input/Output October 11, 2005

Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

Embed Size (px)

Citation preview

Page 1: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 1

APCS-A: Java

Data Conversion & Input/Output

October 11, 2005

Page 2: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 2

Review

• Java Quiz

• Calculator/Graphics Homework

• Last Week’s Lectures: Scope Data Types

Page 3: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 3

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

Page 4: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 4

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?

Page 5: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 5

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 placedouble 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 joinedint z = 43;

System.out.println(“z is” + z);

Page 6: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 6

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 itint 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; ORdouble answer = x / (double) y;

The other variable gets promoted automatically

Page 7: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 7

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 = num1/num2; dResult = num1/num2;dResult = v1/num1;iResult = v1/v2; dResult = v1/v2;dResult = (double) num1/num3;dResult = (int) (val1/num3);iResult = (int) (val1/num3);

Page 8: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 8

Input & Output

• We’ve already done basic output - printing to the terminal windowSystem.out.print(“Hello”);

System.out.println(“ Hello”);

• Let’s look at how to better format the output and how to print some special characters

Page 9: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 9

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

Page 10: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 10

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

Page 11: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 11

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:int i = sc.nextInt();

Page 12: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 12

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

Page 13: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 13

APCS-A: Java

Input/Output Continued

October 12, 2005

Page 14: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 14

Review

• Yesterday we talked about output and using the Scanner class

• Did we all get input from the user?

Page 15: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 15

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();

Page 16: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 16

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

Page 17: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 17

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 a whole number: “);int x = sc.nextInt();

System.out.println(“You entered: “ + x);System.out.println(“Please enter a word followed by enter:

“);String s = sc.next();

System.out.println(“You entered: “ + s);

Page 18: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 18

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 >>

}

Page 19: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 19

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 >>}

Page 20: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 20

Lab / Homework

• Menu Lab: Make a expandable menu class that can be used to run the calculator program

Page 21: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 21

APCS-A: Java

Constructors

October 13, 2005

Page 22: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 22

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

Page 23: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 23

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 variablespublic class Dog{

String name;String breed;public Dog(String name, String dogBreed){

this.name = name;breed = dogBreed;

}}

Page 24: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 24

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

Page 25: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 25

Multiple Constructors

• You can define multiple constructors for an objectpublic 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?

Page 26: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 26

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

Page 27: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 27

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

Page 28: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 28

The Dot Operator

• A Dog remote control would have buttons to do something (to invoke the dog’s methods)

d2.bark();

DOG

Bark

Wag

Eat

Imagine this is a Remote control

Think of the dot operator like pushing a button on a remote control

Page 29: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 29

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

Page 30: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 30

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!

Page 31: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 31

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()

Page 32: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 32

APCS-A: Java

Java API & Strings

October 14, 2005

Page 33: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 33

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?

Page 34: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 34

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/

Page 35: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 35

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

Page 36: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 36

String Class (APCS subset)

Page 37: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 37

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”;

String name

“Jane”

“Jane Dow”

X

name = name + “ Dow”;

Page 38: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 38

Other String Methods (Java API)

• In addition to what the AP people think you need to know, there are some other cool String methods 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

Page 39: Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005

week6 39

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.