This document discusses control structures and data types in Java. It covers logical operators like &&, ||, and ! that can be used to form complex conditional expressions. Selection structures like if, else if, else, and switch statements are explained. Repetition structures like for, while, do-while loops are presented along with examples. Primitive data types like byte, short, int, long, float, double and char are described along with their ranges. The Math class for mathematical functions is also introduced. The document concludes by demonstrating an iterative development process for building software solutions to problems.
This course provides a strong background about JAVA programming language in the field of computing. The course begins with an introductory overview of the Computer and programs, with distinguishes the terms API, IDE and JDK, and gives a comprehensive knowledge about Java development kits and Java integrative development environments like eclipse and NetBeans. Furthermore, the course prepares student to write, compile, run and develop Java applications which are used to find out the solution for several real life problems, in conjunction with using GUI to obtain input, process and display outputs like message dialog boxes, input dialog boxes, confirmation dialog and so on.
JAVA is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
The aim of this course is to explore Java programming fundamentals related to write, compile, run and develop Java applications that are used to discover the solution for several real life problems.
The official learning outcome for this course is: Upon successful completion of the course the students:
• Must know the basic concepts related JAVA programming language.
• Must know how to write, compile, run and develop java applications.
A combination of lectures and practical sessions will be used in this course in order to achieve the aim of the course.
By MSc. Karwan Mustafa Kareem
1 Midterm Preview Time allotted 50 minutes CS 11.docxhoney725342
1
Midterm Preview
Time allotted: 50 minutes
CS 110, Programming Fundamentals I
Central Washington University
Computer Science
Instructions
There are five sections on this exam that contain 24 required questions, a sixth section that contains extra
credit questions, and a last, seventh section, with supplementary information that may be helpful in answering
some of the required questions. This midterm is worth 100 points. Each question in a section is worth the points
indicated at the beginning of the section.
• Pace yourself
• Do not spend too much time on any one question
• Partial credit will be given, if warranted
• Partial credit will NOT be given on the extra credit questions, and points will NOT be taken off for
incorrectly answering an extra credit question
This exam is a closed book, closed notes, no IPhones, no Internet, etc. exam. All that you need is a pen or
pencil.
Name (Print)
Honor Code Statement: I pledge that this submission is solely my work, and that I have neither
given to, nor received help from anyone.
Signature:
Section Question Type Question Numbers Points Possible Points Scored
I True / False 1-10 20
II Multiple Choice 11-15 20
III Find the Error 16 20
IV Short Answer 17-22 30
V One or More Answers 23-24 10
Total 100
VI Extra Credit
Total Including Extra Credit
2
Section I: True/False Each question is worth 2 points; no partial credit given
Circle either True or False.
1. True / False The following is a syntactically correct variable declaration and assignment
statement:
double int = 2.0;
2.
True / False
The diagram in Figure 1a is the decision structure logic of the Java statements in
Figure 1b.
if (Condition_1){
if (Condition_2){
Statement_B;
}else{
Statement_C;
}
}
if (! Condition_1){
Statement_A;
}
Figure 1a Figure 1b
3. True / False Java is a case sensitive programming language.
4. True / False Assuming that letter has been declared as a variable of type char, the below
statement is syntactically correct:
letter = “a”;
5. True / False For the logical AND operator, &&, which connects two boolean expressions, both
expressions must be false for the overall expression to be false.
6. True / False The below two pieces of code output the same thing to the console:
int someVariable = 0;
System.out.println(“Output : “ + someVariable);
int someVar1 = 1, someVar2 = 2;
System.out.println(“Output : “ + someVar1 / someVar2);
7. True / False Syntax errors are mistakes that the programmer has made that violate the rules of the
programming language.
3
8. True / False The following Java code is syntactically incorrect:
Scanner keyBoard = new Scanner(System.in);
int someValue = keyBoard.nextInt();
switch (someValue){
case 1:
case 2:
case 3:
System.out.println("Input is 1 or 2 or 3.");
break;
default:
Syst ...
This course provides a strong background about JAVA programming language in the field of computing. The course begins with an introductory overview of the Computer and programs, with distinguishes the terms API, IDE and JDK, and gives a comprehensive knowledge about Java development kits and Java integrative development environments like eclipse and NetBeans. Furthermore, the course prepares student to write, compile, run and develop Java applications which are used to find out the solution for several real life problems, in conjunction with using GUI to obtain input, process and display outputs like message dialog boxes, input dialog boxes, confirmation dialog and so on.
JAVA is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
The aim of this course is to explore Java programming fundamentals related to write, compile, run and develop Java applications that are used to discover the solution for several real life problems.
The official learning outcome for this course is: Upon successful completion of the course the students:
• Must know the basic concepts related JAVA programming language.
• Must know how to write, compile, run and develop java applications.
A combination of lectures and practical sessions will be used in this course in order to achieve the aim of the course.
By MSc. Karwan Mustafa Kareem
1 Midterm Preview Time allotted 50 minutes CS 11.docxhoney725342
1
Midterm Preview
Time allotted: 50 minutes
CS 110, Programming Fundamentals I
Central Washington University
Computer Science
Instructions
There are five sections on this exam that contain 24 required questions, a sixth section that contains extra
credit questions, and a last, seventh section, with supplementary information that may be helpful in answering
some of the required questions. This midterm is worth 100 points. Each question in a section is worth the points
indicated at the beginning of the section.
• Pace yourself
• Do not spend too much time on any one question
• Partial credit will be given, if warranted
• Partial credit will NOT be given on the extra credit questions, and points will NOT be taken off for
incorrectly answering an extra credit question
This exam is a closed book, closed notes, no IPhones, no Internet, etc. exam. All that you need is a pen or
pencil.
Name (Print)
Honor Code Statement: I pledge that this submission is solely my work, and that I have neither
given to, nor received help from anyone.
Signature:
Section Question Type Question Numbers Points Possible Points Scored
I True / False 1-10 20
II Multiple Choice 11-15 20
III Find the Error 16 20
IV Short Answer 17-22 30
V One or More Answers 23-24 10
Total 100
VI Extra Credit
Total Including Extra Credit
2
Section I: True/False Each question is worth 2 points; no partial credit given
Circle either True or False.
1. True / False The following is a syntactically correct variable declaration and assignment
statement:
double int = 2.0;
2.
True / False
The diagram in Figure 1a is the decision structure logic of the Java statements in
Figure 1b.
if (Condition_1){
if (Condition_2){
Statement_B;
}else{
Statement_C;
}
}
if (! Condition_1){
Statement_A;
}
Figure 1a Figure 1b
3. True / False Java is a case sensitive programming language.
4. True / False Assuming that letter has been declared as a variable of type char, the below
statement is syntactically correct:
letter = “a”;
5. True / False For the logical AND operator, &&, which connects two boolean expressions, both
expressions must be false for the overall expression to be false.
6. True / False The below two pieces of code output the same thing to the console:
int someVariable = 0;
System.out.println(“Output : “ + someVariable);
int someVar1 = 1, someVar2 = 2;
System.out.println(“Output : “ + someVar1 / someVar2);
7. True / False Syntax errors are mistakes that the programmer has made that violate the rules of the
programming language.
3
8. True / False The following Java code is syntactically incorrect:
Scanner keyBoard = new Scanner(System.in);
int someValue = keyBoard.nextInt();
switch (someValue){
case 1:
case 2:
case 3:
System.out.println("Input is 1 or 2 or 3.");
break;
default:
Syst ...
The Three Basic Selection Structures in C++ Programming ConceptsTech
Now check the powerpoint presentation about selection structures in programming. For more visit www.techora.net
Three types of selection structures are available like :
1 - Sequence Structure
2 - Selection Strcuture
3 - Repetition Structure
In this PPT slide, we discuss about the selection structure
1 - if statements
2 - if else statement
3 - switch statement
Have you ever seen a Java course that is 'visual' in nature? The kind of lessons where you can see what happens when you are creating an object, doing method overloading, and using run-time polymorphism. I bet you haven't. Welcome to the most 'visual' Java course you will ever take.
This course teaches you everything you need to get started with Java programming. It divides each topic into explanation and example.
The explanation section deals with how a particular concept works in Java and covers the following:
Data Types & Variables, Typecasting,
Operators & Conditional statements such as if, if else, switch
Loops such as for, for each, while, and do while
Methods, Types of methods, Call by Value vs. Call by Reference, Variable Scope, Method Overloading,
Arrays and ArrayLists,
Classes and objects, How classes and objects work, and How primitive types vs. reference types are stored
Swing classes to take input from the user and command line methods to take input from the user such as BufferedReader, Scanner, Console,
Static variables, static methods, this keyword, super keyword, method overriding,
What is inheritance
And a real world example of run-time polymorphism that actually demonstrates what happens with vs. without polymorphism.
The example section covers an example for every concept discussed above. The course will be updated constantly to keep in sync with the real world developments in Java. So, are you ready to become a Java PRO?
The first lecture of the ACM Aleppo CPC training. The local contest of ICPC. This lecture will help you get started in programming contests word with the lower bound techniques. The lectures focus on the C++ programming language and the STL library to solve programming problems.
GridMate - End to end testing is a critical piece to ensure quality and avoid...ThomasParaiso2
End to end testing is a critical piece to ensure quality and avoid regressions. In this session, we share our journey building an E2E testing pipeline for GridMate components (LWC and Aura) using Cypress, JSForce, FakerJS…
The Three Basic Selection Structures in C++ Programming ConceptsTech
Now check the powerpoint presentation about selection structures in programming. For more visit www.techora.net
Three types of selection structures are available like :
1 - Sequence Structure
2 - Selection Strcuture
3 - Repetition Structure
In this PPT slide, we discuss about the selection structure
1 - if statements
2 - if else statement
3 - switch statement
Have you ever seen a Java course that is 'visual' in nature? The kind of lessons where you can see what happens when you are creating an object, doing method overloading, and using run-time polymorphism. I bet you haven't. Welcome to the most 'visual' Java course you will ever take.
This course teaches you everything you need to get started with Java programming. It divides each topic into explanation and example.
The explanation section deals with how a particular concept works in Java and covers the following:
Data Types & Variables, Typecasting,
Operators & Conditional statements such as if, if else, switch
Loops such as for, for each, while, and do while
Methods, Types of methods, Call by Value vs. Call by Reference, Variable Scope, Method Overloading,
Arrays and ArrayLists,
Classes and objects, How classes and objects work, and How primitive types vs. reference types are stored
Swing classes to take input from the user and command line methods to take input from the user such as BufferedReader, Scanner, Console,
Static variables, static methods, this keyword, super keyword, method overriding,
What is inheritance
And a real world example of run-time polymorphism that actually demonstrates what happens with vs. without polymorphism.
The example section covers an example for every concept discussed above. The course will be updated constantly to keep in sync with the real world developments in Java. So, are you ready to become a Java PRO?
The first lecture of the ACM Aleppo CPC training. The local contest of ICPC. This lecture will help you get started in programming contests word with the lower bound techniques. The lectures focus on the C++ programming language and the STL library to solve programming problems.
GridMate - End to end testing is a critical piece to ensure quality and avoid...ThomasParaiso2
End to end testing is a critical piece to ensure quality and avoid regressions. In this session, we share our journey building an E2E testing pipeline for GridMate components (LWC and Aura) using Cypress, JSForce, FakerJS…
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Communications Mining Series - Zero to Hero - Session 1DianaGray10
This session provides introduction to UiPath Communication Mining, importance and platform overview. You will acquire a good understand of the phases in Communication Mining as we go over the platform with you. Topics covered:
• Communication Mining Overview
• Why is it important?
• How can it help today’s business and the benefits
• Phases in Communication Mining
• Demo on Platform overview
• Q/A
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Sudheer Mechineni, Head of Application Frameworks, Standard Chartered Bank
Discover how Standard Chartered Bank harnessed the power of Neo4j to transform complex data access challenges into a dynamic, scalable graph database solution. This keynote will cover their journey from initial adoption to deploying a fully automated, enterprise-grade causal cluster, highlighting key strategies for modelling organisational changes and ensuring robust disaster recovery. Learn how these innovations have not only enhanced Standard Chartered Bank’s data infrastructure but also positioned them as pioneers in the banking sector’s adoption of graph technology.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
java switch
1. 4. More Control Structures and
Types
4.1 Logical (Conditional) AND, OR, and NOT
4.2 Nested Ifs and the Switch Statement
4.3 The For and Do-While Loops
4.4 Additional Primitive Types
4.5 Using the Math Library
4.6 Solving Problems with Java: An Iterative
Development Cycle
2. Objectives
• Learn useful selection and repetition
statement
• Use primitive types and operators
• Use the Math library
• Build software using an iterative
development cycle
3. Logical Operators
• Boolean expressions can use logical (conditional)
! Logical NOT
&& Logical AND
|| Logical OR
• They all take boolean operands and produce
boolean results
• Logical NOT (Conditional Complement) is a
unary operator (one operand), but the other two
are binary operators (two operands)
4. Logical Operators
• Conditions in selection statements and loops can
use logical operators to form complex expressions
if (b >= a && c >= a)
min = a;
if (a >= b && c >= b)
min = b;
if (a >= c && b >= c)
min = c;
• Logical operators have precedence relationship
between themselves and other operators
5. Symbol Meaning Example
&& conditional AND (age > 20) && (age < 35)
|| conditional OR (height > 78.5) || (weight > 300)
Figure 4.2 Conditional Operators
6. age age > 20 age < 35 age > 20 && age < 35
10 false true false
25 true true true
40 true false false
Figure 4.3 Evaluating an example of a conditional AND expression
7. A B A && B
true true true
true false false
false (don't care) false
Figure 4.4 Evaluating a conditional AND expression
8. height weight height > 78.5 weight > 300 (height>78.5) || (weight>300)
62 125 false false false
80 250 true false true
72 310 false true true
80 325 true true true
Figure 4.5 Evaluating an example of a conditional OR expression
9. A B A || B
true (don't care) true
false true true
false false false
Figure 4.6 Evaluating a condition OR expression
12. if (score >= 60 && score < 80)
System.out.println("Score " + score + " receives a C");
else
System.out.println("Score " + score + " receives a B or an A");
Figure 4.9 If-else statement to choose between two alternatives
13. Nested If Statements
• The if-true-statement and if-false-statement of an
if statement could be another if statement
• These are called nested if statements
if (a >= b)
if (b >= c) min = c;
else min = b;
else
if (a >= c) min = c;
else min = a;
• An else clause is matched to the last unmatched if
(no matter what the indentation implies)
14. Figure 4.10 Nested if-else statement to choose among three alternatives
if (score >= 60 && score < 80)
System.out.println("Score " + score + " receives a C");
else if (score >=80 && score < 90)
System.out.println("Score " + score + " receives a B");
else
System.out.println("Score " + score + " receives an A");
15. Figure 4.11 Improved version of Figure 4.10
if (score >= 60 && score < 80)
System.out.println("Score " + score + " receives a C");
else if (score >=80 && score < 90)
System.out.println("Score " + score + " receives a B");
else if (score >= 90 && score <= 100)
System.out.println("Score " + score + " receives an A");
17. Figure 4.13 Incorrect attempt to pair an else with an if
if (score >= 60)
if (score >= 80)
System.out.println("You got a B or an A");
else
System.out.println("You got a D or an F"); // Wrong pairing
18. Figure 4.14 Corrected pairing of else and if
if (score >= 60)
if (score >= 80)
System.out.println("You got a B or an A");
else
System.out.println("You got a C"); // Correct pairing
19. Figure 4.15 Figure 4.13 rewritten as an if-else with nested if
if (score >= 60) {
if (score >= 80)
System.out.println("You got a B or an A");
}
Else
// Paired to first 'if'
System.out.println("You got a D or an F");
20. The Switch Statement
• The switch statement provides another means 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 list
associated with the first value that matches
21. The Switch Statement
• A switch statement can have an optional default
case which has no associated value
• If the default case is present, control will transfer
to it if no other case value matches
• The default case can be positioned anywhere in
the switch, it is usually placed at the end
• If there is no default case, and no other value
matches, control falls through to the next
statement after the switch
22. 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
• The expression of a switch statement must result
in an integral data type, like an integer or character
• You cannot perform relational checks with a
switch staement
23. Figure 4.16 An example of a switch statement
switch(mark) {
case 0:
case 1:
case 2:
case 3:
case 4: System.out.println("F");
break;
case 5: System.out.println("D");
break;
case 6:
case 7: System.out.println("C");
break;
case 8: System.out.println("B");
break;
case 9:
case10: System.out.println("A");
break;
default:System.out.println("Incorrect score");
}
24. The For Statement
• The for statement has the following syntax:
for ( initialization ; condition ; increment )
statement ;
• The initialization is executed once before the loop
begins
• The statement is executed until the condition
becomes false
• The increment portion is executed at the end of
each iteration
25. The For Statement
• The for statement is equivalent to the following
while loop structure
initialization ;
while ( condition )
{
statement ;
increment ;
}
• Like a while loop, the condition of a for loop is
tested prior to executing the loop body
• Therefore, the body of a for loop can be
executed zero or more times
26. Figure 4.17 A for statement for the sum 1+2+3+4
int sum = 0;
for (int i = 1; i <= 4; i++)
sum += i;
27. initialize i = 1
test 1 <= 4 is true
execute body sum += 1 (result: sum = 0 + 1 = 1)
update i++ (result: i = 2)
test 2 <= 4 is true
execute body sum += 2 (result: sum = 1 + 2 = 3)
update i++ (result: i = 3)
test 3 <= 4 is true
execute body sum += 3 (result: sum = 3 + 3 = 6)
update i++ (result: i + 4)
test 4 <= 4 is true
execute body sum += 4 (result: sum = 6 + 4 = 10)
update i++ (result: i = 5)
test 5 <= 4 is false
Figure 4.18 Trace of execution of the for loop of Figure 4.17
28. Figure 4.19 A for statement for the sum 1+3+5+7+9
int sum = 0;
for (int i = 1; i < 10; i += 2)
sum += i;
29. Figure 4.20 A for statement for the sum 4+3+2+1
int sum = 0;
for (int i = 4; i >= l; i--)
sum += i;
30. Figure 4.21 Declaring an index variable before the for loop
int i; // declare loop index
int sum = 0;
for (i = 4; i >= 1; i--) // initialize loop index
sum += i;
...
i += 17; // use variable i
32. The StringTokenizer Class
• StringTokenizer(String str)
Constructor. Creates a new StringTokenizer object to parse str based
on white space
• StringTokenizer(String str, String delimiter)
Constructor. Creates a new StringTokenizer object to parse str based
on specified set of delimiteds
• int countTokens()
Returns the number of token still left to be processed in the string
• boolean hasMoreTokens()
Returns true if there are tokens still left to be processed in the string
• String nextToken()
Returns the next token in the string
33. Figure 4.22 Syntax for the do-while statement
do
statement
while (condition) ;
34. Do-while Statement
• A do-while statement checks the condition after
executing the loop body
• The loop body of a do-while statement is executed
at least once
• Do-while statements are suitable for writing loops
that are executed at least once
• DoGrowth.java
• Babylonian.java (extra)
35. Figure 4.23 Pseudocode for example 4.5 enhancement
do {
Compute balance as in Example 4.5
Ask the user -- Repeat or Quit?
} while (User chooses to repeat);
36. The char Type
• Java uses Unicode charater set (16 bits)
• ASCII, American Standard Code for Information
Interchange, is a seven-bit code used by other
language like C and C++
• ASCII is a subset of Unicode
• Keyword char to denote character type
• Character constants are quoted in single quotes,
e.g. ‘A’
• Ascii.java
37. Escape Sequence
• Escape sequence: preceding certain character with
the escape character for special meaning
• The newline, 'n', positions the next output at
the start of the next line
• The return, 'r', positions the next output at the
start of the curent line
• The backspace, 'b', positions the next output
one character to the left
• The tab, 't', position the next output at the next
tab position
38. Escape Sequence
• The escape needs to be "escaped" when quoted
like '' and ""
• The single quote character must be "escaped" in
single quotes like '''
• The double quote must be "escaped" in double
quotes like ””This is a quote”"
• Special.java
39. backlash
Special
Character
Meaning
n newline, move to the start of the next line
t tab
b backspace
r return, move to the start of the current line
" double quote
n newline, move to the start of the next line
Figure 4.24 Escape sequences for special characters
40. The byte, short, and long Types
• byte: one byte = 8 bits, range from -128 to 127
• short: two bytes = 16 bits
– range from -32,768 to 32,767
• int: four bytes = 32 bits
– range from -2,147,483,648 to 2,147,483,647
• long: eight bytes = 64 bits
– range 9,223,372,036,854,808 to 9,223,372,036,854,807
• int is the default for integer constant
• Integer constants can be made long by adding the
suffix l or L
41. The float Type
• float: four bytes = 32 bits
– Exponent can range from -45 to 48
– Min ~ -3.4E+38 with seven significant digits
– Max ~ 3.4E+38 with seven significant digits
• double: eight bytes = 64 bits
– Exponent can range from -324 to 308
– Min ~ -1.7E+308 with 16 significant digits
– Max ~ 1.7E+308 with 16 significant digits
• double is the default for real constants
• Make a number float by adding an f or F suffix
float good = 4.25f; // valid
float ok = (float)4.25; // valid
float bad = 4.25; // invalid
42. The Math Class
• In java.lang package
• Two static constants: E (base of natural log) and
PI (ratio of circumference of a circle to its
diameter)
• General functions
abs - absolute value
ceil - ceiling, smallest integer >= argument
floor - flooring, greatest integer <= argument
round - rounding, integer closest to argument
max - maximum of the two arguments
min - minimum of the two arguments
43. The Math Class
• Simple mathematical operations
sqrt(double a) - Return the square root of the argument
pow(double a, double b) - Returns of value of the first
argument raised to the power of the second argument
log(double a) - Returns the natural logarithm (base e) of
a double value
exp(double a) - Returns the exponential number e (i.e.,
2.718...) raised to the power of a double value
• Random number
random() - Returns a double value with a positive sign,
greater than or equal to 0.0 and less than 1.0
44. The Math Class
• Trigonometric functions
sin, cos, tan - sine, cosine, and tangent
asin, acos, atan- arc-sine, arc-cosine, and arc-tangent
atan2(double a, double b) - Returns the theta
component in the polar coordinates (r, theta)
corresponding to the point (b, a) in Cartesian
coordinates
• Degree/Radian conversion
toDegrees(double angrad) - Converts an angle in
radians to the equivalent angle measured in degrees
toRadians(double angdeg) - Converts an angle in
degrees to the equivalent angle measured in radians
46. Figure 4.25 Size of the reward given each day
1
1
2
4
8
12 16
16
8
4
2
Days
47. Figure 4.26 Using random numbers to represent heads and tails
0.0 0.5 1.0
HHHHHHHHHHHHHHHHHTTTTTTTTTTTTTTTTTT
Heads Tails
48. Iterative Development Cycle
• First iteration - CovertMenu.java (with stubs for
methods)
• Second iteration - CovertFromMetric.java
(implement MetricToEnglish())
• Third iteration - Convert.java (implement
EnglishToMetric())
49. Figure 4.27 Iterative problem-solving process
Formulate the problem;
do {
Develop pseudocode;
Implement pseudocode in Java program;
Test program;
while (More subproblems to refine);
50. Figure 4.28 Top-level Pseudocode
do [
Display the menu;
Get the user's choice;
Execute the user's choice;
} while (user does not choose to quit);
51. Figure 4.29 Pattern for a menu-driven application
do {
System.out.println();
System.out.println("Choose from the following list");
System.out.println("1. Convert from meters to yds,ft,in");
System.out,println("2. Convert from yds,ft,in to meters");
System.out.println("3. Quit");
int choice = Io.readInt("Enter your choice, 1, 2 or 3");
switch (choice) {
case 1:
MetricToEnglish();
break;
case 2:
EnglishToMetric();
break;
case 3: System.out.println("Bye, Have a nice day");
}
} while (choice != 3);
52. Figure 4.30 Pseudocode for the MetricToEnglish method
Input the number of meters, x, to convert;
Convert x meters to y yards;
Separate y into yInteger yards and yFraction yards;
Convert yFraction yards to f feet.
Separate f into fInteger feet and fFraction feet.
Convert fFraction feet to i inches.
Display the output.
53. Figure 4.31 Refinement:Display the output
if (yInteger > 0)
if (yInteger <= 1) Display yInteger yard;
else Display yInteger yards;
if (fInteger > 0)
if (fInteger <= 1) Display fInteger foot;
else Display fInteger feet;
if (i >0)
if (i <= 1) Display i inch;
else Display i inches;
if (yInteger == 0 && fInteger == 0 && i == 0)
Display 0 yards;
54. Figure 4.32 Pseudocode for the EnglishToMetric method
Input yards, feet, and inches to convert;
Convert to inches;
Convert inches to meters;
Output the result;