450 likes | 453 Views
Learn the basic sequence, selection, and repetition statements in Java. Study applets and how to draw various shapes. Understand debugging techniques and handling floating-point numbers.
E N D
3. S/E with Control Structures • 3.1 Relational Operators and Expressions • 3.2 If and if-else Statements • 3.3 The Type Double • 3.4 Program Design with the While Loop • 3.5 Debugging • 3.6 Getting Started with Objects and Applets: Drawing Shapes
Objectives • Learn the basic sequence, selection, and repetition statements • Identify objects and their responsibilities • Simple debugging techniques • Handle floating-point numbers • Study applets, draw various shapes
3.1 Relational Operators and Expressions • Relational operators include: <, <=, >, >=, ==, and != • Each relational operator takes two operands and gives a boolean value: true or false • Be careful not to confuse == with = • Relational operators have precedence lower than arithmetic operators but higher than assignment operators
Operator Symbol Meaning Example < less than 31 < 25 is false <= less than or equal to 464 <= 7213 is true > greater than -98 > -12 is false >= greater than or equal to 9 >= 99 is false == equal to 9 == 12 + 12 is false != not equal to 292 != 377 is true Figure 3.2 Java relational and equality operators
Control Flow • The order Java executes the statements of a program is sequential if not told otherwise int item1 = 25; int item2 = 12; item2 = item1 + 15; • Conditional statement like the if and if-else statements allow us to make decision • They change the default control flow
Entry int item1 = 25; int item2 = 12; Item2 = item1+15; Exit Figure 3.3 The sequence control flow
3.2 The if and if-else statements • The syntax if ( condition ) if_true_statement; [ else if_false_statement; ] • condition must be boolean: true or false • If condition is true, if_true_statement is executed; if the condition is false, if_false_statement is executed • One or the other will be executed, but not both
condition if_true_statement False Figure 3.4 Control flow for the if statement
The if Statement: Example hours = Integer.parseInt(input); if (hours > 40) System.out.println(“You worked overtime “ + “this week”); System.out.println(“You worked “ + hours + “ hours”);
hours = Integer.parselnt(input); True Hours>40 System.out.println(“You “ + “worked overtime this week”) False System.out.println( “you worked ” + hours + “ hours”); Figure 3.5 Control Flow for Example 3.2
True False Condition if_true_statement if_false_statement Figure 3.6 Flow chart for the if-else statement
The if-else Statement: Example if (hours <= 40) wage = hourlyRate * hours; else wage = hourlyRate * 40 + hourlyRate * 1.5 * (hours - 40);
Block Statements • Several statements can be grouped together into a block statement • A block is delimited by braces ( { … } ) • A block statement can be used wherever a statement is called for in the Java syntax • For example, in an if-else statement, the if-portion, or the else-portion, or both, could be block statements
True Z <= 10 x = 2; y = 7; False Figure 3.7 Flow chart for if statement with block, step 1
True Z <= 10 x = 2; False y = 7; Figure 3.8 Flow chart if statement with block, step 2
Block Statements • Use a consistent style for blocks if (x < 10) { y = 5; z = 8; } else { y = 9; z = -2; } if (x < 10) { y = 5; z = 8; } else { y = 9; z = -2; }
3.3 The Type Double • Scientific (floating-point) notation for real numbers: 123.45 and 0.0012345 can be written respectively as 0.12345E3 0.12345E-2 • 0.12345 is the mantissa, 3 and -2 are the exponents, with the implicit base of 10 • Scientific notation is good for numbers with very small or very large absolute value • Java has type double that provides 16 decimal digits accurately.
public class Triangle { private double side1, side2, side3; public Triangle(double a, double b, double c) { side1 = a; side2 = b; side3 = c; } public double circumference() { return side1 + side2 + side3; } public double area() { double s = circumference() / 2.0; return Math.sqrt(s*(s - side1)*(s - side2)*(s - side3)); } }
Double Value Output • When printed using print or println methods of System.out, Java prints double values using the most convenient format • Scientific format for numbers greater than 10,000,000 or less than -10,000,000, and for numbers between -.001 and .001. • Java treats decimal literals as type double • Java does not print trailing zeroes • Type double is accurate to 16 significant digits • The 17th digit may be rounded
Input and Formatted Output import javax.swing.*; import java.text.*; … public static void main(String[] args) { NumberFormat nf = NumberFormat.getCurrentcyInstance(); String s = JOptionPane.showInputDialog(“Hours worked? “); double hours = Double.parseDouble(s); JOptionPane.showMessageDialog (null, “Your pay is “ + nf.format(hours * 5.5)); System.exit(0); }
Formatted Output • The NumberFormat class has static methods that return formatter object getCurrencyInstance() getPercentInstance() • Each formatter object has a method called format that returns a string with the specific information in the appropriate format • The DecimalFormat class can be used to format a floating point value in generic way • The DecimalFormat class takes a string that represents a pattern for the formatted number
Data Conversions • Sometimes it is convenient to convert data from one type to another • Conversion must be handled carefully to avoid losing information • Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int) • Narrowing conversions can lose information because they tend to go from a larger data type to a smaller one (such as an int to a short)
Data Conversions • In Java, data conversions can occur in three ways: • assignment conversion • arithmetic promotion • casting • Assignment conversion occurs when a value of one type is assigned to a variable of another type • Only widening conversion can happen via assignment • Arithmetic promotion happens automatically when operators in expressions converts their operands • Casting is the most powerful, and dangerous, technique for conversion result = (float) total / count;
2.54 Original expression + 361 2.54 After Conversion + 361.0 Figure 3.9 Conversion of mixed-mode expression
3.4 The While Loop • Repetition statements allow us to execute a statement multiple times repetitively • They are often referred to as loops • Like if-else statements, they are controlled by boolean expressions’ • Java has three kinds of repetition statements: the while loop, the do loop, and the for loop • The while loop has this syntax while(condition) while_true_statement;
The While Loop • If the condition is true, the statement is executed • Then the condition is evaluated again • The statement is executed repetitively until the condition becomes false • If the condition is false initially, then the statement is never executed • The body of a while loop must eventually make the condition false • If not, it is an infinite loop, which is a common logical error unless you are absolutely sure it is not
False True Condition while_true_statement Figure 3.10 Flow chart for the while loop
Problem Solving • The purpose of writing a program is to solve a problem • The general steps in problem solving are: • Understand the problem • Dissect the problem • Design a solution • Consider alternatives to the solution and refine it • Implement the solution • Test the solution and fix and problems that exist
Problem Solving • Many software development project failed because the developers didn’t understand the problems to be solved • Avoid assumptions and clarify ambiguities • As problems and their solutions becomes larger, we must organize our development into manageable pieces • We will dissect our solutions into pieces called classes and objects, taking an object-orientedapproach
Program Development • The creation of software involves four basic activities: • establishing the requirements • creating a design • implementing the code • testing the implementation • Real development process is much more involved than this, but these four steps are a good starting point
Requirements • Requirements specify the tasks a program must accomplish (what to do, not how to do it) • They often include description of the user interface • The initial requirements must be critiqued, modified, and expanded • It is often difficult to establish detailed, unambiguous, and complete requirements • Careful attention to the requirements can save significant time and money in the overall project
Design • An algorithm is a step-by-step process for solving a problem • A program follow one or more algorithms • The design of a program specifies the algorithms and data needed • In object-oriented development, the design establishes the classes, their data and methods • The details of a method may be expressed in pseudocode, which is code-like, but does not necessarily follow any specific syntax
Implementation • Implementation is the process of translating a design into source code • Most novice programmers think that writing code is the heart of software development, but it is actually the least creative step • Almost all important decisions are made during requirements analysis and design • Implementation should focus on coding details, including guidelines, clarity, maintainability, expandability, and documentation
Testing • A program should be executed multiple times with various input in an attempt to find errors • Debugging is the process of discovering the cause of a problem and fix it • Debugging can only indicate the presence of errors (bugs), but not the absence • Don’t ever think there is only one more bug to fix • tests should focus on design details as well as overall requirements
Read the quantity of scores; while (count < quantity) { Read the next score; Add the score to the total so far; Increment the count of scores; } Display the quantity and the total; Figure 3.11 Pseudocode for the sum of test scores problem
3.5 Debugging • Syntax error • caught by the compiler • easy to fix • Run-time error • reported at run-time by interpreter • often depending on input and environment • usually cause program to terminate immaturely • Logical error • program runs but results are wrong • can be very difficult to find and/or fix • Requirement error • disastrous
3.6 Getting Started with Applets • A java application is a stand-alone program with a main method • An applet is a Java program that is intended to be transported over the web and executed using a web browser • An applet doesn’t have a main method • Instead, there are several special methods that serve specific purposes • The paint method, for instance, is automatically executed and is used to draw the applets contents
Drawing Shapes • The paint method accepts a parameter that is an object of the Graphics class • A Graphics object defines a graphical context on which we can draw shapes and text • The Graphics class has several methods for drawing shapes • The class that defines the applet extends the Applet class • This makes use of inheritance, an object-oriented concept to be explored later
(70,80) (130,230) Figure 3.12 Drawing a line
200 (50,50) 100 Figure 3.13 Drawing a rectangle
90º 180º 0º 270º Figure 3.15 Degree measure around a circle
90º 45º Figure 3.16 An arc from the oval of Figure 3.14
Dimension d = getSize(); int w = d.width; int h = d.height; g.drawRect(2*w/3,0,w/3,h/3); Figure 3.19 Drawing a rectangle relative to the applet's size