SlideShare ist ein Scribd-Unternehmen logo
1 von 45
Lesson 4
Outline
Formatting Output
Boolean Expressions
The if Statement
Comparing Data
The switch Statement
Anatomy of a Method
Anatomy of a Class
Encapsulation
2
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
3
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 ...
}
switch
and
case
are
reserved
words
If expression
matches value2,
control jumps
to here
4
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
5
The switch Statement
switch (option)
{
case 'A':
aCount++;
break;
case 'B':
bCount++;
break;
case 'C':
cCount++;
break;
}
• An example of a switch statement:
6
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
7
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
8
//********************************************************************
// 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
9
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.");
}
}
}
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.");
}
}
}
Sample Run
Enter a numeric grade (0 to 100): 91
That grade is well above average. Excellent.
11
Outline
Formatting Output
Boolean Expressions
The if Statement
Comparing Data
The switch Statement
Anatomy of a Method
Anatomy of a Class
Encapsulation
12
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
13
//********************************************************************
// 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 14
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);
}
}
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);
}
}
Sample Run
I'm thinking of a number between 1 and 10. Guess what it is: 6
That is not correct, sorry.
The number was 9
16
myMethod();
myMethodcompute
Method Control Flow
• If the called method is in the same class,
only the method name is needed
17
doIt helpMe
helpMe();obj.doIt();
main
Method Control Flow
• The called method is often part of another
class or object
18
Method Header
• A method declaration begins with a method
header
char calc (int num1, int num2, String message)
method
name
return
type
parameter list
The parameter list specifies the type
and name of each parameter
The name of a parameter in the method
declaration is called a formal parameter
19
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 expression
must be consistent with
the return type
sum and result
are local data
They are created
each time the
method is called, and
are destroyed when
it finishes executing
20
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
21
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");
22
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
23
//********************************************************************
// 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
24
//-----------------------------------------------------------------
// 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);
}
}
25
//-----------------------------------------------------------------
// 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);
}
}
26
Sample Run
Enter a number : 2
The result is .2000
Enter a number: -2
The result is : -1000
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"
27
Outline
Formatting Output
Boolean Expressions
The if Statement
Comparing Data
The switch Statement
Anatomy of a Method
Anatomy of a Class
Encapsulation
28
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
29
Examples of Classes
30
Classes
• A class can contain data declarations and
method declarations
int size, weight;
char category;
Data declarations
Method declarations
31
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
32
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
33
//********************************************************************
// 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
34
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);
}
}
35
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;
}
}
36
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
37
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
38
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
39
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
40
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
41
Quick Check
What is the relationship between a class and an
object?
42
Quick Check
What 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.
43
Quick Check
Where is instance data declared?
What is the scope of instance data?
What is local data?
44
Quick Check
Where is instance data declared?
What is the scope of instance data?
What is local data?
At the class level.
It can be referenced in any method of the class.
Local data is declared within a method, and is
only accessible in that method.
45

Weitere ähnliche Inhalte

Was ist angesagt?

Notes: Verilog Part 2 - Modules and Ports - Structural Modeling (Gate-Level M...
Notes: Verilog Part 2 - Modules and Ports - Structural Modeling (Gate-Level M...Notes: Verilog Part 2 - Modules and Ports - Structural Modeling (Gate-Level M...
Notes: Verilog Part 2 - Modules and Ports - Structural Modeling (Gate-Level M...Jay Baxi
 
Control structures ii
Control structures ii Control structures ii
Control structures ii Ahmad Idrees
 
Control structures in java
Control structures in javaControl structures in java
Control structures in javaVINOTH R
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in JavaRavi_Kant_Sahu
 
itft-Decision making and branching in java
itft-Decision making and branching in javaitft-Decision making and branching in java
itft-Decision making and branching in javaAtul Sehdev
 
Storage Classes and Functions
Storage Classes and FunctionsStorage Classes and Functions
Storage Classes and FunctionsJake Bond
 
Process synchronization
Process synchronizationProcess synchronization
Process synchronizationAli Ahmad
 
PLSQL CURSOR
PLSQL CURSORPLSQL CURSOR
PLSQL CURSORArun Sial
 
Introducing generic types
Introducing generic typesIntroducing generic types
Introducing generic typesIvelin Yanev
 
Process Synchronization
Process SynchronizationProcess Synchronization
Process SynchronizationSonali Chauhan
 
OCA JAVA - 2 Programming with Java Statements
 OCA JAVA - 2 Programming with Java Statements OCA JAVA - 2 Programming with Java Statements
OCA JAVA - 2 Programming with Java StatementsFernando Gil
 
java programming- control statements
 java programming- control statements java programming- control statements
java programming- control statementsjyoti_lakhani
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statementsKuppusamy P
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in JavaNiloy Saha
 

Was ist angesagt? (20)

Notes: Verilog Part 2 - Modules and Ports - Structural Modeling (Gate-Level M...
Notes: Verilog Part 2 - Modules and Ports - Structural Modeling (Gate-Level M...Notes: Verilog Part 2 - Modules and Ports - Structural Modeling (Gate-Level M...
Notes: Verilog Part 2 - Modules and Ports - Structural Modeling (Gate-Level M...
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
 
itft-Decision making and branching in java
itft-Decision making and branching in javaitft-Decision making and branching in java
itft-Decision making and branching in java
 
Mule expression
Mule expressionMule expression
Mule expression
 
Storage Classes and Functions
Storage Classes and FunctionsStorage Classes and Functions
Storage Classes and Functions
 
Jsp session 11
Jsp   session 11Jsp   session 11
Jsp session 11
 
Functions
FunctionsFunctions
Functions
 
Process synchronization
Process synchronizationProcess synchronization
Process synchronization
 
Control statements in java programmng
Control statements in java programmngControl statements in java programmng
Control statements in java programmng
 
PLSQL CURSOR
PLSQL CURSORPLSQL CURSOR
PLSQL CURSOR
 
Introducing generic types
Introducing generic typesIntroducing generic types
Introducing generic types
 
Process Synchronization
Process SynchronizationProcess Synchronization
Process Synchronization
 
OCA JAVA - 2 Programming with Java Statements
 OCA JAVA - 2 Programming with Java Statements OCA JAVA - 2 Programming with Java Statements
OCA JAVA - 2 Programming with Java Statements
 
java programming- control statements
 java programming- control statements java programming- control statements
java programming- control statements
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
C functions list
C functions listC functions list
C functions list
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Control statement-Selective
Control statement-SelectiveControl statement-Selective
Control statement-Selective
 

Andere mochten auch

Parte 7 - Los Archivos Hamilton
Parte 7 - Los Archivos HamiltonParte 7 - Los Archivos Hamilton
Parte 7 - Los Archivos Hamiltoncienciaspsiquicas
 
20150318 hve smb john schalken
20150318 hve smb   john schalken20150318 hve smb   john schalken
20150318 hve smb john schalkenSMBBV
 
June 2009 to june 2012 past papers v2
June 2009 to june 2012 past papers v2June 2009 to june 2012 past papers v2
June 2009 to june 2012 past papers v2ppermaul
 
Deducción natural (estrategias)
Deducción natural (estrategias)Deducción natural (estrategias)
Deducción natural (estrategias)Faraón Llorens
 
BSG Financial Solutions Client Proposition 2015
BSG Financial Solutions Client Proposition 2015BSG Financial Solutions Client Proposition 2015
BSG Financial Solutions Client Proposition 2015Mark Huddleston
 
Veterans Annual report 2015 Latest edition 1st June 15
Veterans Annual report 2015 Latest edition 1st June 15Veterans Annual report 2015 Latest edition 1st June 15
Veterans Annual report 2015 Latest edition 1st June 15Dave Smith
 
NancyKuzavaDesignPMPresentationLI
NancyKuzavaDesignPMPresentationLINancyKuzavaDesignPMPresentationLI
NancyKuzavaDesignPMPresentationLINancy Kuzava
 
Seema Singh- Insights from a recent successful applicant
Seema Singh- Insights from a recent successful applicantSeema Singh- Insights from a recent successful applicant
Seema Singh- Insights from a recent successful applicantProfessor Priscilla Harries
 

Andere mochten auch (12)

Parte 7 - Los Archivos Hamilton
Parte 7 - Los Archivos HamiltonParte 7 - Los Archivos Hamilton
Parte 7 - Los Archivos Hamilton
 
20150318 hve smb john schalken
20150318 hve smb   john schalken20150318 hve smb   john schalken
20150318 hve smb john schalken
 
Participantes DIY
Participantes DIYParticipantes DIY
Participantes DIY
 
June 2009 to june 2012 past papers v2
June 2009 to june 2012 past papers v2June 2009 to june 2012 past papers v2
June 2009 to june 2012 past papers v2
 
Cordoba
CordobaCordoba
Cordoba
 
Deducción natural (estrategias)
Deducción natural (estrategias)Deducción natural (estrategias)
Deducción natural (estrategias)
 
BSG Financial Solutions Client Proposition 2015
BSG Financial Solutions Client Proposition 2015BSG Financial Solutions Client Proposition 2015
BSG Financial Solutions Client Proposition 2015
 
Veterans Annual report 2015 Latest edition 1st June 15
Veterans Annual report 2015 Latest edition 1st June 15Veterans Annual report 2015 Latest edition 1st June 15
Veterans Annual report 2015 Latest edition 1st June 15
 
NancyKuzavaDesignPMPresentationLI
NancyKuzavaDesignPMPresentationLINancyKuzavaDesignPMPresentationLI
NancyKuzavaDesignPMPresentationLI
 
Seema Singh- Insights from a recent successful applicant
Seema Singh- Insights from a recent successful applicantSeema Singh- Insights from a recent successful applicant
Seema Singh- Insights from a recent successful applicant
 
Analysing Poster - 4018
Analysing Poster - 4018Analysing Poster - 4018
Analysing Poster - 4018
 
Julia Fox Rushby - a Panel Judge's insights
Julia Fox Rushby - a Panel Judge's insights Julia Fox Rushby - a Panel Judge's insights
Julia Fox Rushby - a Panel Judge's insights
 

Ähnlich wie Ifi7107 lesson4

Java Chapter 04 - Writing Classes: part 4
Java Chapter 04 - Writing Classes: part 4Java Chapter 04 - Writing Classes: part 4
Java Chapter 04 - Writing Classes: part 4DanWooster1
 
Java Chapter 05 - Conditions & Loops: part 5
Java Chapter 05 - Conditions & Loops: part 5Java Chapter 05 - Conditions & Loops: part 5
Java Chapter 05 - Conditions & Loops: part 5DanWooster1
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statementsVladislav Hadzhiyski
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysDevaKumari Vijay
 
Md06 advance class features
Md06 advance class featuresMd06 advance class features
Md06 advance class featuresRakesh Madugula
 
Ive posted 3 classes after the instruction that were given at star.pdf
Ive posted 3 classes after the instruction that were given at star.pdfIve posted 3 classes after the instruction that were given at star.pdf
Ive posted 3 classes after the instruction that were given at star.pdfdeepaarora22
 
Chapter 2.2
Chapter 2.2Chapter 2.2
Chapter 2.2sotlsoc
 
Ifi7184 lesson3
Ifi7184 lesson3Ifi7184 lesson3
Ifi7184 lesson3Sónia
 
Swift - the future of iOS app development
Swift - the future of iOS app developmentSwift - the future of iOS app development
Swift - the future of iOS app developmentopenak
 
09 implementing+subprograms
09 implementing+subprograms09 implementing+subprograms
09 implementing+subprogramsbaran19901990
 
Intro to tsql unit 11
Intro to tsql   unit 11Intro to tsql   unit 11
Intro to tsql unit 11Syed Asrarali
 

Ähnlich wie Ifi7107 lesson4 (20)

Java Chapter 04 - Writing Classes: part 4
Java Chapter 04 - Writing Classes: part 4Java Chapter 04 - Writing Classes: part 4
Java Chapter 04 - Writing Classes: part 4
 
Java Chapter 05 - Conditions & Loops: part 5
Java Chapter 05 - Conditions & Loops: part 5Java Chapter 05 - Conditions & Loops: part 5
Java Chapter 05 - Conditions & Loops: part 5
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statements
 
Ppt on java basics1
Ppt on java basics1Ppt on java basics1
Ppt on java basics1
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
Md06 advance class features
Md06 advance class featuresMd06 advance class features
Md06 advance class features
 
Ive posted 3 classes after the instruction that were given at star.pdf
Ive posted 3 classes after the instruction that were given at star.pdfIve posted 3 classes after the instruction that were given at star.pdf
Ive posted 3 classes after the instruction that were given at star.pdf
 
Chapter 2.2
Chapter 2.2Chapter 2.2
Chapter 2.2
 
Ppt on java basics
Ppt on java basicsPpt on java basics
Ppt on java basics
 
java Statements
java Statementsjava Statements
java Statements
 
SQL / PL
SQL / PLSQL / PL
SQL / PL
 
Ifi7184 lesson3
Ifi7184 lesson3Ifi7184 lesson3
Ifi7184 lesson3
 
C language
C languageC language
C language
 
Lesson 5
Lesson 5Lesson 5
Lesson 5
 
Swift - the future of iOS app development
Swift - the future of iOS app developmentSwift - the future of iOS app development
Swift - the future of iOS app development
 
09 implementing+subprograms
09 implementing+subprograms09 implementing+subprograms
09 implementing+subprograms
 
Oracle: Cursors
Oracle: CursorsOracle: Cursors
Oracle: Cursors
 
Oracle:Cursors
Oracle:CursorsOracle:Cursors
Oracle:Cursors
 
Intro to tsql unit 11
Intro to tsql   unit 11Intro to tsql   unit 11
Intro to tsql unit 11
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 

Kürzlich hochgeladen

Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Anthony Dahanne
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 

Kürzlich hochgeladen (20)

Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 

Ifi7107 lesson4

  • 2. Outline Formatting Output Boolean Expressions The if Statement Comparing Data The switch Statement Anatomy of a Method Anatomy of a Class Encapsulation 2
  • 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 3
  • 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 ... } switch and case are reserved words If expression matches value2, control jumps to here 4
  • 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 5
  • 6. The switch Statement switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; } • An example of a switch statement: 6
  • 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 7
  • 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 8
  • 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 9
  • 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."); } } } 10
  • 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 Run Enter a numeric grade (0 to 100): 91 That grade is well above average. Excellent. 11
  • 12. Outline Formatting Output Boolean Expressions The if Statement Comparing Data The switch Statement Anatomy of a Method Anatomy of a Class Encapsulation 12
  • 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 13
  • 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 14
  • 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); } } 15
  • 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 Run I'm thinking of a number between 1 and 10. Guess what it is: 6 That is not correct, sorry. The number was 9 16
  • 17. myMethod(); myMethodcompute Method Control Flow • If the called method is in the same class, only the method name is needed 17
  • 18. doIt helpMe helpMe();obj.doIt(); main Method Control Flow • The called method is often part of another class or object 18
  • 19. Method Header • A method declaration begins with a method header char calc (int num1, int num2, String message) method name return type parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal parameter 19
  • 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 expression must be consistent with the return type sum and result are local data They are created each time the method is called, and are destroyed when it finishes executing 20
  • 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 21
  • 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"); 22
  • 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 23
  • 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 24
  • 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); } } 25
  • 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); } } 26 Sample Run Enter a number : 2 The result is .2000 Enter a number: -2 The 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" 27
  • 28. Outline Formatting Output Boolean Expressions The if Statement Comparing Data The switch Statement Anatomy of a Method Anatomy of a Class Encapsulation 28
  • 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 29
  • 31. Classes • A class can contain data declarations and method declarations int size, weight; char category; Data declarations Method declarations 31
  • 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 32
  • 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 33
  • 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 34
  • 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); } } 35
  • 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; } } 36
  • 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 37
  • 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 38
  • 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 39
  • 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 40
  • 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 41
  • 42. Quick Check What is the relationship between a class and an object? 42
  • 43. Quick Check What 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. 43
  • 44. Quick Check Where is instance data declared? What is the scope of instance data? What is local data? 44
  • 45. Quick Check Where is instance data declared? What is the scope of instance data? What is local data? At the class level. It can be referenced in any method of the class. Local data is declared within a method, and is only accessible in that method. 45