0% found this document useful (0 votes)
22 views22 pages

Control Structures and Classes Tutorial

This document covers topics related to control structures, objects, and classes in Java. It includes examples of if/else statements, while loops, do-while loops, and for loops. It also discusses the anatomy of a basic class, including data members, constructors, and methods. It provides exercises for students to practice using control structures and designing simple classes. It outlines Problem Set 2 which involves creating banking and investment classes, using loops and random numbers, and calculating compound interest over multiple periods.

Uploaded by

Wilver Icban
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views22 pages

Control Structures and Classes Tutorial

This document covers topics related to control structures, objects, and classes in Java. It includes examples of if/else statements, while loops, do-while loops, and for loops. It also discusses the anatomy of a basic class, including data members, constructors, and methods. It provides exercises for students to practice using control structures and designing simple classes. It outlines Problem Set 2 which involves creating banking and investment classes, using loops and random numbers, and calculating compound interest over multiple periods.

Uploaded by

Wilver Icban
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.00/1.

001 Tutorial 2

Control, Objects & Classes

September 20, 2005

1
Topics

• Control Structures
• Objects and Classes

• Problem Set 2

2
Control Structures: Branch

(Review)

if (boolean){

statement;}

if (boolean) {

statement1;}

else{

statement2;}

3
Control Structures: Branch

(Review)

if (boolean1){

statement1;}

else if (boolean2){

statement2;}

else if (booleanN){

statementN;}

else {statement;}

4
Control Structures –

Branch Example

//A simple (and somewhat silly) example

int x = Integer

.parseInt(JOptionPane

.showInputDialog(“Enter any integer.”))

if(x<0)

[Link](“Integer less than 0”);

else if(x>0)

[Link](“Integer greater than 0”);

else

[Link](“Integer equals 0”);

5
Control Structures: Iteration (1)

while (boolean){

statement;

/*Executes statement until

boolean is false. If boolean

is initially false, loop

never executes.*/

6
Control Structures - Exercise 1

Use a while loop to add numbers from 1

to 10 and print the result.

7
Control Structures: Iteration (2)

do{

statement;

} while (boolean);

/*Executes statement until

boolean is false. If boolean

is initially false, loop will

execute once.*/

8
Control Structures - Exercise 2

Repeat Exercise 1, using a do…while


loop.

9
Control Structures: Iteration (3)

for(start_expr; end_bool; cont_expr)

statement; }

/*Starting at start_expr, statement

& cont_expr are executed until

end_bool is false. If end_bool is

initially false, loop never

executes.*/

10
Control Structures - Exercise 3

Repeat Exercise 1, using a for loop.

11
Control Structures - Exercise 4

• Upgrade your solution to Exercise 1, so


your program now prints whether the
result is even or odd number. (Hint: use
branching.)

12
Classes and Objects

We’ve already met some classes and objects:

• Class: JOptionPane, String


• Object: “What is your name?” (String object)

What are classes and objects?


• Classes are patterns
– blueprints & specifications
• Objects are instances of classes
– A skyscraper (built using blueprints and

specifications)

13
Classes and Objects cont’d

What does a class definition usually contain?

• Constructor to create an instance of class

– The process of building a skyscraper


• Data member to hold information about an
object
– A skyscraper has a height, a mass, a certain
number of windows
• Method to invoke behavior on object

– A skyscraper sways

14
Anatomy of Class

public class ClassName {

Data Members

Constructor

Methods

15
Example of Class

public class Student {

//data members

private int ID;

public String name;

//constructor

public Student (int i,String s ) {

ID = i;

name = s;}

//methods

public int yourID() {return ID;}

16
Create and Use Instance (Object)

• Keyword new

Student dave = new

Student(12,”Dave”);

• . operator

int id = [Link]();

[Link]([Link]+”\t”

+id);

17
Exercise 4

• Let’s design our tutorial section


- Determine the types of objects
- Identify data members for each object
- Identify methods for each object

18
Problem Set 2

• Theme: Banking & Investment


– Creating classes and data members
– Looping
• Calculating interest
• [Link]()

19
Problem Set 2 cont’d

• Interest Calculation

Balance at beginning of period = $1000


Interest rate for period = 3%
Interest = $1000 × 3% = $30
Balance at end of period = $1000 + $30 = $1030
OR

Balance at end of period = (100%+3%) × $1000 =

$1030

Interest = $1030 - $1000 = $30

20
Problem Set 2 cont’d

• [Link]()

– Takes no arguments
– Returns a double between 0 and 1

4+6*[Link]() gives a number in


what range?
How would you generate a random number
between 50 and 100?
21
Exercise 5

Exercise:
• Initial investment = $2,500

• Interest rate fluctuates between 3 and


5% in any period
• What is the final value of the investment
and interest accrued at the end of 10
periods?

22

Common questions

Powered by AI

Control structures in programming are essential for directing the flow of execution and can be categorized mainly into two types: branching and iteration. In branching, the program decides which path to take based on the evaluation of a boolean expression. Examples include simple if-else structures, such as 'if (boolean1) { statement1;} else if (boolean2) { statement2; } else { statement; }' which allows the program to choose between different execution paths . For iteration, control structures like 'while', 'do...while', and 'for' loops repeat a series of statements as long as a specified condition evaluates to true. For example, 'while (boolean) { statement; }' executes a statement until the boolean condition becomes false . Each of these structures allows for more complex and dynamic program flows, from making decisions to automating repetitive tasks.

Constructors are special methods in a class definition tasked with initializing new objects when they are created. They set initial values for data members and perform any setup necessary for the object's use. For instance, in the 'Student' class, the constructor 'public Student(int i, String s)' initializes the 'ID' and 'name' data members with the provided arguments . Constructors are essential because they ensure that objects start in a coherent state, reducing the likelihood of errors and simplifying object instantiation by handling necessary initial configurations. Without constructors, manual setup would be prone to errors and inconsistencies, increasing the complexity of managing object states.

The 'for' loop is structured with an initialization expression, a termination condition, and an update expression, all specified in its syntax: 'for(start_expr; end_bool; cont_expr) { statement; }' . This contrasts with 'while' and 'do...while' loops, which separate initialization and updating from the loop's condition check, potentially scattering these statements throughout the loop body. The 'for' loop is particularly useful when the number of iterations is known beforehand, allowing for concise and clear code. It is favored over 'while' or 'do...while' loops in cases where iteration involves simple counting or when managing counters and termination conditions within a single line is beneficial for readability and maintenance.

Branching and iteration complement each other by combining decision-making with repeated actions, essential for solving complex problems. Branching structures guide the execution path based on conditional checks, while iteration facilitates operation repetition until a condition changes. An example integrating both concepts could be sorting numbers and distinguishing even and odd sums. Using a 'for' loop to iterate over numbers and 'if-else' to check number properties, one could both calculate the sum 'for(int i=1; i<=10; i++){ sum += i; }' and determine parity 'if(sum % 2 == 0) { System.out.println("Even"); } else { System.out.println("Odd"); }' . This demonstrates how branching informs direction within broader repetitive operations, empowering sophisticated program flows.

The 'new' keyword is crucial in object-oriented programming as it is used to create a new instance of a class, allocating memory for this new object. By invoking the constructor, 'new' initializes the object's data members and prepares it for use. For instance, 'Student dave = new Student(12, "Dave");' creates a new 'Student' object 'dave' with specific 'ID' and 'name' attributes . Once instantiated, methods can be called on the object using the dot operator to perform actions or retrieve data, such as 'System.out.println(dave.name + "\t" + id);', which accesses and interacts with the object's data . This process makes the object functional and integral to leveraging the class's encapsulated features.

'Math.random()' generates a pseudorandom double value between 0.0 (inclusive) and 1.0 (exclusive). To produce a random number within a specific range [min, max], the expression 'min + (max-min)*Math.random()' scales the random value to fit this range . In financial simulations, this technique is useful for modeling scenarios such as fluctuating interest rates or stock prices. For example, to simulate an interest rate varying from 3% to 5%, we can compute '3 + (5-3)*Math.random()', producing a rate randomly distributed within the desired range . This flexibility becomes invaluable for creating robust models that mimic and predict real-market behaviors, incorporating stochastic elements.

The primary difference between a 'while' loop and a 'do...while' loop lies in their condition checking mechanism and execution guarantee. In a 'while' loop, the condition is checked before executing the loop body, which means the loop may not execute at all if the condition is initially false. Its syntax is 'while (boolean) { statement; }' . In contrast, a 'do...while' loop checks the condition after executing the loop body, guaranteeing at least one execution of the loop body regardless of the initial condition. This loop is structured as 'do { statement; } while (boolean);' . Consequently, using 'do...while' is suitable when the statements need to be executed at least once, whereas 'while' is preferred when pre-execution condition checks are critical to avoid unnecessary loop entries.

Encapsulation, a cornerstone of object-oriented programming, refers to the bundling of an object's data and the methods that operate on that data within a single unit or class. By restricting direct access to some of the object's components and only allowing manipulation through defined methods, encapsulation enhances security and maintainability. For example, data members like 'private int ID' in a 'Student' class are not directly accessible from outside the class, while methods such as 'public int yourID()' provide controlled access to these private data members . This separation between an object's interface and implementation details helps protect against unintended interference, allowing developers to modify internal workings without affecting other parts of a program.

Calculating interest accumulation over multiple periods with varying interest rates involves applying the formula for compound interest iteratively, adjusting the rate each time. Starting with an initial balance, the interest for each period is computed using the current balance multiplied by the fluctuating interest rate. For example, given an initial investment of $2,500 and interest rates between 3% and 5%, the balance at the end of each period can be updated as follows: new_balance = current_balance * (1 + random_rate). Random number generation comes into play when determining the interest rate for each period using 'Math.random()' to generate a value, adjusted to fit the desired range (e.g., between 3% and 5%). This approach models real-world financial scenarios where interest rates fluctuate and accurately simulates the growth of investments over time.

Using classes and objects in programming is crucial because they enable object-oriented design, which emphasizes modularity, reuse, and abstraction. Classes provide blueprints for creating objects, encapsulating data, and functionalities within them. Typically, a class contains data members to store object attributes, constructors to instantiate objects, and methods to define behaviors. For instance, a class 'Student' may include data members like 'int ID,' a constructor to initialize these members, and methods like 'yourID()' to perform actions on the object's state . This structure ensures code reusability, improves maintainability, and reflects real-world entities, facilitating a clear and organized approach to complex software development.

You might also like