Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Week61 APCS-A: Java Data Conversion & Input/Output October 11, 2005."— Presentation transcript:

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

2 week62 Review Java Quiz Calculator/Graphics Homework Last Week’s Lectures:  Scope  Data Types

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

4 week64 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?

5 week65 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 is” + z);

6 week66 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 double answer = x / (double) y; The other variable gets promoted automatically

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

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

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

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

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

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

13 week613 APCS-A: Java Input/Output Continued October 12, 2005

14 week614 Review Yesterday we talked about output and using the Scanner class Did we all get input from the user?

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

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

17 week617 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);

18 week618 If Statements Do you remember how we handled conditionals in Alice? If statements have a similar syntax and usage in Java if ( > ) { > } else { > }

19 week619 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 ( > ) { > } else if ( >) { > } else { > }

20 week620 Lab / Homework Menu Lab: Make a expandable menu class that can be used to run the calculator program

21 week621 APCS-A: Java Constructors October 13, 2005

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

23 week623 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; }

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

25 week625 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?

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

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

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

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

30 week630 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!

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

32 week632 APCS-A: Java Java API & Strings October 14, 2005

33 week633 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?

34 week634 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/

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

36 week636 String Class (APCS subset)

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

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

39 week639 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.


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

Similar presentations


Ads by Google