Upload
fernando-loizides
View
168
Download
1
Embed Size (px)
Citation preview
2
OutlineFormatting Output
Boolean Expressions
The if Statement
Comparing Data
The switch Statement
Anatomy of a Method
Anatomy of a Class
Encapsulation
3
The switch Statement• The switch statement provides another way to
decide which statement to execute next
• The switch statement evaluates an expression, then attempts to match the result to one of several possible cases
• Each case contains a value and a list of statements
• The flow of control transfers to statement associated with the first case value that matches
4
The switch Statement• The general syntax of a switch statement is:
switch ( expression ){ case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ...
}
switchandcaseare
reservedwords
If expressionmatches value2,control jumpsto here
5
The switch Statement• Often a break statement is used as the last
statement in each case's statement list
• A break statement causes control to transfer to the end of the switch statement
• If a break statement is not used, the flow of control will continue into the next case
• Sometimes this may be appropriate, but often we want to execute only the statements associated with one case
6
The switch Statement
switch (option){ case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break;}
• An example of a switch statement:
7
The switch Statement• A switch statement can have an optional
default case
• The default case has no associated value and simply uses the reserved word default
• If the default case is present, control will transfer to it if no other case value matches
• If there is no default case, and no other value matches, control falls through to the statement after the switch
8
The switch Statement• The type of a switch expression must be integers,
characters, or enumerated types
• As of Java 7, a switch can also be used with strings
• You cannot use a switch with floating point values
• The implicit boolean condition in a switch statement is equality
• You cannot perform relational checks with a switch statement
• See GradeReport.java
9
//********************************************************************// GradeReport.java Author: Lewis/Loftus//// Demonstrates the use of a switch statement.//********************************************************************
import java.util.Scanner;
public class GradeReport{ //----------------------------------------------------------------- // Reads a grade from the user and prints comments accordingly. //----------------------------------------------------------------- public static void main (String[] args) { int grade, category;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter a numeric grade (0 to 100): "); grade = scan.nextInt();
category = grade / 10;
System.out.print ("That grade is ");
continue
10
continue
switch (category) { case 10: System.out.println ("a perfect score. Well done."); break; case 9: System.out.println ("well above average. Excellent."); break; case 8: System.out.println ("above average. Nice job."); break; case 7: System.out.println ("average."); break; case 6: System.out.println ("below average. You should see the"); System.out.println ("instructor to clarify the material " + "presented in class."); break; default: System.out.println ("not passing."); } }}
11
continue
switch (category) { case 10: System.out.println ("a perfect score. Well done."); break; case 9: System.out.println ("well above average. Excellent."); break; case 8: System.out.println ("above average. Nice job."); break; case 7: System.out.println ("average."); break; case 6: System.out.println ("below average. You should see the"); System.out.println ("instructor to clarify the material " + "presented in class."); break; default: System.out.println ("not passing."); } }}
Sample RunEnter a numeric grade (0 to 100): 91That grade is well above average. Excellent.
12
Outline
Formatting Output
Boolean Expressions
The if Statement
Comparing Data
The switch Statement
Anatomy of a Method
Anatomy of a Class
Encapsulation
13
Method Declarations
• Let’s now examine methods in more detail
• A method declaration specifies the code that will be executed when the method is invoked (called)
• When a method is invoked, the flow of control jumps to the method and executes its code
• When complete, the flow returns to the place where the method was called and continues
• The invocation may or may not return a value, depending on how the method is defined
14
//********************************************************************// Guessing2.java Author: Adapted from Lewis/Loftus//// Demonstrates the use of a block statement in an if-else.//********************************************************************
import java.util.*;
public class Guessing2{ static void checkGuess(int, answer, int, guess) { if (guess == answer) System.out.println ("You got it! Good guessing!"); else { System.out.println ("That is not correct, sorry."); System.out.println ("The number was " + answer); } }
//----------------------------------------------------------------- // Plays a simple guessing game with the user. //----------------------------------------------------------------- public static void main (String[] args) { final int MAX = 10; int answer, guess;
continue
15
Continue
Scanner scan = new Scanner (System.in); Random generator = new Random();
answer = generator.nextInt(MAX) + 1;
System.out.print ("I'm thinking of a number between 1 and " + MAX + ". Guess what it is: ");
guess = scan.nextInt(); checkGuess(answer,guess);
}}
16
Continue
Scanner scan = new Scanner (System.in); Random generator = new Random();
answer = generator.nextInt(MAX) + 1;
System.out.print ("I'm thinking of a number between 1 and " + MAX + ". Guess what it is: ");
guess = scan.nextInt(); checkGuess(answer,guess);
}}
Sample RunI'm thinking of a number between 1 and 10. Guess what it is: 6That is not correct, sorry.The number was 9
17
myMethod();
myMethodcompute
Method Control Flow• If the called method is in the same class, only
the method name is needed
18
doIt
helpMe
helpMe();
obj.doIt();
main
Method Control Flow• The called method is often part of another
class or object
19
Method Header• A method declaration begins with a method header
char calc (int num1, int num2, String message)
methodname
returntype
parameter list
The parameter list specifies the typeand name of each parameter
The name of a parameter in the methoddeclaration is called a formal parameter
20
Method Body• The method header is followed by the method body
char calc (int num1, int num2, String message)
{ int sum = num1 + num2; char result = message.charAt (sum);
return result;}
The return expressionmust be consistent withthe return type
sum and resultare local data
They are created each time the method is called, and are destroyed when it finishes executing
21
The return Statement• The return type of a method indicates the
type of value that the method sends back to the calling location
• A method that does not return a value has a void return type
• A return statement specifies the value that will be returned
return expression;
• Its expression must conform to the return type
22
Parameters• When a method is called, the actual
parameters in the invocation are copied into the formal parameters in the method header
char calc (int num1, int num2, String message)
{ int sum = num1 + num2; char result = message.charAt (sum);
return result;}
ch = obj.calc (25, count, "Hello");
23
Local Data• As we’ve seen, local variables can be declared
inside a method
• The formal parameters of a method create automatic local variables when the method is invoked
• When the method finishes, all local variables are destroyed (including the formal parameters)
• Keep in mind that instance variables, declared at the class level, exists as long as the object exists
24
//********************************************************************// testMethod.java Author: Isaias Barreto da Rosa//// Demonstrates the use of methods.//********************************************************************
package testmethod;import java.util.Scanner;public class TestMethod { //----------------------------------------------------------------- // Receives one integer as parameter and multiply it by 1000 // if it is positive and by 500 if it is negative //----------------------------------------------------------------- static int executeFormula(int x) { int result; if (x>0) result = x*1000; else result = x*500; return result; }
continue
25
//----------------------------------------------------------------- // Reads one integers from the user and multiply it by 1000 // if it is positive and by 500 if it is negative (by calling // executeFormula) //-----------------------------------------------------------------
public static void main(String[] args) { int value; int r; Scanner scan = new Scanner(System.in); System.out.println("write a number"); value = scan.nextInt(); r = executeFormula(value); System.out.println("The result is: "+r); }}
26
//----------------------------------------------------------------- // Reads one integers from the user and multiply it by 1000 // if it is positive and by 500 if it is negative (by callin TestMethod) //-----------------------------------------------------------------
public static void main(String[] args) { int value; int r; Scanner scan = new Scanner(System.in); System.out.println("write a number"); value = scan.nextInt(); r = executeFormula(value); System.out.println("The result is: "+r); }}
Sample RunEnter a number : 2The result is .2000Enter a number: -2The result is : -1000
27
Lexicographic Ordering• Lexicographic ordering is not strictly alphabetical
when uppercase and lowercase characters are mixed
• For example, the string "Great" comes before the string "fantastic" because all of the uppercase letters come before all of the lowercase letters in Unicode
• Also, short strings come before longer strings with the same prefix (lexicographically)
• Therefore "book" comes before "bookcase"
28
Outline
Formatting Output
Boolean Expressions
The if Statement
Comparing Data
The switch Statement
Anatomy of a Method
Anatomy of a Class
Encapsulation
29
Writing Classes• The programs we’ve written in previous
examples have used classes defined in the Java standard class library
• Now we will begin to design programs that rely on classes that we write ourselves
• The class that contains the main method is just the starting point of a program
• True object-oriented programming is based on defining classes that represent objects with well-defined characteristics and functionality
31
Classes• A class can contain data declarations and
method declarations
int size, weight;char category;
Data declarations
Method declarations
32
Classes• The values of the data define the state of an
object created from the class
• The functionalities of the methods define the behaviors of the object
33
Classes• We’ll want to design the Student class so
that it is a versatile and reusable resource
• Any given program will probably not use all operations of a given class
• See StudentManager.java
34
//********************************************************************// StudentManager.java Author: Isaias Barreto da Rosa//// Demonstrates the creation and use of a user-defined class.//********************************************************************
package studentmanager;import java.util.Scanner;public class StudentManager {
//----------------------------------------------------------------- // Compares the grades of two students and tells who is the best //----------------------------------------------------------------- static void compareStudents(Student st1, Student st2) { if (st1.getGrade() > st2.getGrade()) { System.out.print(st1.getName +" is a better student");} else { if (st2.getGrade() > st1.geGrade()) {System.out.print(st2.getName() +" is a better student");} else {System.out.println(st1.getNname() + " and " + st2.getName()
+ "are on the same level");} } }continue
35
Continue
public static void main(String[] args) { Student st1, st2, st3; String name; double grade; Scanner scan = new Scanner(System.in); System.out.println("Insert the first name for Student 1"); name = scan.nextLine(); System.out.println("Insert the grade for Student 1"); grade = scan.nextDouble(); st1 = new Student(name,grade); System.out.println("Insert the first name for Student 2"); name = scan.nextLine(); System.out.println("Insert the grade for Student 2"); grade = scan.nextDouble(); st2 = new Student(name,grade);
compareStudents(st1,st2); }}
36
continue
class Student{ private String name; private double grade; public final double MAXGRADE=20; //----------------------------------------------------------------- // Constructor: Sets the student’s name and initial grade. //----------------------------------------------------------------- public Student (String name1, double grade1) { name = name1; grade = grade1; } //----------------------------------------------------------------- // Returns the student's name //----------------------------------------------------------------- String getName() { return name; } //----------------------------------------------------------------- // Returns the student's grade //----------------------------------------------------------------- double getGrade() { return grade; } //----------------------------------------------------------------- // Increase the studens's grade //----------------------------------------------------------------- double increaseGrade() { if (grade < MAXGRADE);
{grade++;} return grade; } }
37
The Student Class• The Student class contains two data
values
– a String name that represents the student's name
– an double grade that represents the student’s grade
38
Constructors• As mentioned previously, a constructor is
used to set up an object when it is initially created
• A constructor has the same name as the class
• The Student constructor is used to set the name and the initial grade
39
Data Scope• The scope of data is the area in a program in
which that data can be referenced (used)
• Data declared at the class level can be referenced by all methods in that class
• Data declared within a method can be used only in that method
• Data declared within a method is called local data
• In the compareStudents class, the variable scan is declared inside the main method -- it is local to that method and cannot be referenced anywhere else
40
Instance Data• A variable declared at the class level (such as name)
is called class attribute or instance variable
• Each instance (object) has its own instance variable
• A class declares the type of the data, but it does not reserve memory space for it
• Each time a Student object is created, a new name variable is created as well
• The objects of a class share the method definitions, but each object has its own data space
• That's the only way two objects can have different states
41
Instance Data• We can depict the two Student objects from
the StudentManager program as follows:
st1 Johnname
st2 Maryname
Each object maintains its own name variable, and thus its own state
43
Quick CheckWhat is the relationship between a class and an object?
A class is the definition/pattern/blueprint of an object. It defines the data that will be managed by an object but doesn't reserve memory space for it. Multiple objects can be created from a class, and each object has its own copy of the instance data.
44
Quick CheckWhere is instance data declared?
What is the scope of instance data?
What is local data?