1 / 48

APCS-AB: Java

APCS-AB: Java. Data Types, Returns, Scope October 11, 2005. 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

albert
Download Presentation

APCS-AB: Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. APCS-AB: Java Data Types, Returns, Scope October 11, 2005

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

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

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

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

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

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

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

  9. 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 = (double) x / (double) y;

  10. 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?)

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

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

  13. 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)

  14. 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?

  15. Scope public class ScopeClass { int x = -1; String s = “gook ”; public void scopeFunc1() { String s = “Gobble-D ”; System.out.println(s + x); scopeFunc2(42); } public void scopeFunc2(int x) { System.out.println(s+x); } } Question #1 Question #2 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()?

  16. 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)

  17. 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;

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

  19. APCS-AB: Java Constructors & Lab October 12, 2005

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

  21. 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; } }

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

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

  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?

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

  26. APCS-AB: Java Input/Output & Debugging October 13, 2005

  27. Review • Fantasy Football Design • Player • Team • League • 80 point quiz

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

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

  30. The Dot Operator • A Dog remote control would have buttons to do something (to invoke the dog’s methods) Dog myDog = new Dog(); myDog.bark(); DOG Eat Wag Bark Think of the dot operator like pushing a button on a remote control Imagine this is a Remote control

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

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

  33. 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 programmer-defined object to print nicely, we need to provide the following method in the classes we define: public String toString() { }

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

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

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

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

  38. 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: \n>“); int x = sc.nextInt(); System.out.println(“You entered: “ + x); System.out.println(“Please enter a word followed by enter: \n>“); String s = sc.next(); System.out.println(“You entered: “ + s);

  39. APCS-AB: Java Input/Output & Random October 14, 2005

  40. Review • Scanner Class

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

  42. 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); } }

  43. 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 • 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))

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

  45. 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!

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

  47. 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)

  48. Weekend Homework • Finish Menu Lab

More Related