您的位置:首页 > 编程语言 > Java开发

Notes for Java(Part b)

2006-09-24 02:43 369 查看
三、Program control: Decisions and operators
Formatting output
• Define a pattern that represents how the output should look
• # represents a character where no leading or trailing zeroes are printed, and decimals are rounded
– for the pattern “###.##” 2.100000000000 will print as 2.1
• 0 represents a character where leading or trailing zeros are printed
– for the pattern “000.00” 2.100000000000 will print as 002.10
• , represents a comma inserted for a number > 999
– for the pattern “,###.00” 555212.0 will print as 555,212.00
Creating objects
• Last week you created objects of the String class
String title = “hello”;
• Now we need to learn to create other objects
• The usual way is:
Class object = new contructor(parameters)
• (note the constuctor has the same name as the Class)
Formatting Output
• DecimalFormat class is imported from java.text
DecimalFormat object = new DecimalFormat (String pattern)
DecimalFormat fmt = new DecimalFormat(“0.00”);
The format method
• The DecimalFormat class has a method called format()
• This is applied to the data that we want to format eg area and returns a String containing the formatted number
String format (double number)
DecimalFormat fmt = new DecimalFormat(“0.00”);
System.out.println ("The circle area: " + fmt.format(area));

Flaow of Control
• Unless indicated otherwise, the order of statement execution through a method is linear:
– one after the other in the order they are written
• Some programming statements modify that order, allowing us to:
– decide whether or not to execute a particular statement (this week)
– perform a statement over and over repetitively (next week)
Boolean Expressions
• A condition often uses one of Java's equality operators or relational operators, which all return boolean results:
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
• Note the difference between the equality operator (==) and the assignment operator (=)
Conditional Statements
• A conditional statement lets us choose which statement will be executed next
– ie give us the power to make decisions
• Java's conditional statements are
– the if statement,
– the if-else statement,
– the switch statement
if ( condition ) statement;
if (testResult > 0)
total = total + testResult;
System.out.println ("The final mark is " + total);
Common Errors
• Assignment and equals
if (total = 100) System.out.println(“congratulations!”);
• This is not a condition
• It is an assignment and will not compile
• The empty statement
if (total > 100);
System.out.println(“congratulations!”);
• In Java semicolons don’t go at the end of each line but
– at the end of each complete declaration or statement
• This does not give a compiler error
• It is interpreted as “if true do nothing”
• What about multiple true statements?
if (total > 100)
System.out.println(“congratulations!”);
System.out.println(“you’re a genius!”);
• The second print line will always print
• For multiple statements we use a block
Block Statements
• Several statements can be grouped into a block statement
• A block is delimited by curly braces { … }
• A block statement can be used wherever a statement is called for in the Java syntax
if (temp > 40)
{
System.out.println(“get a drink”);
System.out.println(“get a book”);
System.out.println(“relax!”);
}
• For consistency a block can be used for a single statement
The if-else Statement
• An else clause can be added to an if statement to make it an if-else statement:
if ( condition )
statement1;
else
statement2;
• If the condition is true, statement1 is executed; if the condition is false, statement2 is executed
• One or the other will be executed, but not both
• Align the else under the if
Comparing Strings for equality
• As a String is an object not a primitive type
– Use the equals(String object) method to compare for equality
String myName = “Rumplestiltskin”;
String yourName = JOptionPane.showInputDialog(“Enter your name”);
if (yourName.equals(myName))
System.out.println(“Our names are the same”);
else
System.out.println(“Our names are different”);
• Also see the method equalsIgnoreCase(String object)
String answer = JOptionPane.showInputDialog(“Do you want to continue? (y/n): ”);
if (answer.equalsIgnoreCase(“y”)
The switch Statement
• A better means of comparing a variable (or an expression) against a set of possible values
• Matches the result to one of several possible cases
• The expression eg day must result in a data type char, byte, short or int;
• it cannot be a floating point value
switch (day)
{
case 1: System.out.println("Sunday");
case 2: System.out.println("Monday");
case 3: System.out.println("Tuesday");
case 4: System.out.println("Wednesday");
case 5: System.out.println("Thursday");
case 6: System.out.println("Friday");
case 7: System.out.println("Saturday");
}
• A match is a start point for execution
• Processing will continue into the following cases
• A break statement causes control to transfer to the end of the switch statement
Logical Operators
• Boolean expressions (ie expressions evaluating to true or false) can use the following logical operators :
&& Logical AND
|| Logical OR
! Logical NOT
• Logical operators have precedence relationships between themselves and other operators
• Always use brackets to clearly show your intention

Highest * / %
+ -
> < >= <=
== !=
&&
||
Lowest =

四、Repetition, Program Design and Testing
Repetition Statements
• Repetition statements or “loops” allow us to execute a statement or block multiple times
• Like if statements, they are controlled by boolean expressions
– ie. they cause a single statement or block to be executed repeatedly while an expression is true
• Java has three kinds of repetition statements:
– the while loop,
– the do loop,
– the for loop

• The programmer needs to consider the right kind of loop for the situation
The while Statement
• The while statement has the following syntax:
while ( condition )
statement;
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.
• The condition in a while statement must return a boolean
• If the condition of a while statement is false initially, the statement is never executed
– so the body of a while loop will execute zero or more times
• Something in the body of a while loop must alter the value of the control condition to stop the loop iterations
• The repetition of a loop can be
– Count controlled or
– Event controlled
Count controlled while loop
int count ;
count = 1; // initialise loop variable
while ( count <= 3 ) // test expression (loops 3 times)
{
System.out.println( “count is “ + count ); // repeated action
count = count + 1 ; // update loop variable
}
System.out.println( “Done” );
Event controlled loop
• Used when the number of iterations is unknown
• Again, something in the body of the loop causes the condition to be false
• Often we use a variable called a sentinel
– “one who keeps watch…a sentry” Chambers Dictionary
• Keep looping until the value of the sentinel indicates that processing should stop

• Requires initialising the sentinel before entering the loop

• Requires reviewing the sentinel as the last statement in the loop

• The body of a while loop must eventually make the condition false

• If not, it is an infinite loop, which will execute until the user interrupts the program

• Ensure that your loops will terminate normally
The do Statement
• The do statement has the following syntax:
do
{
statement;
}
while ( condition )
The statement is executed once initially, then the condition is evaluated
The statement is repetitively executed until the condition becomes false
• A do loop is similar to a while loop, except that the condition is evaluated after the body of the loop is executed
• Therefore the body of a do loop will execute at least one time
Displaying a question
• To display a dialog box containing a specified question and Yes/No/Cancel button options.
For example
again = JOptionPane.showConfirmDialog (null, "Do Another?");
• Returns constants YES_OPTION, NO_OPTION, CANCEL_OPTION,
The for Statement
• The for statement has the following syntax:
for ( initialization ; condition ; increment )
statement;
The initialization portion
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
• A for loop is equivalent to the following while loop structure:
initialization;
while ( condition )
{
statement;
increment;
}
• Therefore you never need to use a for loop - but programmers like them
Nested Loops
• Similar to nested if statements, loops can be nested as well
• That is, the body of a loop could contain another loop
• For each single time through the outer loop, the inner loop will go through its entire set of iterations

while (outer loop condition)
{
. . .
while (inner loop condition)
{
. . .
}
. . .
}

Which Loop to use?
• for loop
– If the number of repetitions is known
• while loop
– If the number of repetitions is not known
• do-while loop
– Use instead of while if the loop body has to be executed before the continuation condition is tested
Finding logic errors
• Be careful of one-off errors ie. the loop executes one to few or one too many times

• If you are having problems debugging, insert System.out.println() statements into your code
– to print the value of a loop counter variable,
– a sentinel
– or any other relevant variables that will help you track each iteration
Using BlueJ Debugger
• Demonstrate BlueJ debugger (eg OddEven)
• A debugger is an essential tool for finding logic errors
• What functions does it provide?
– Setting breakpoints
• This stops program execution at this point and displays the code
• Click in the area to the left of the text in the text editor
– Stepping through the code
• Step line by line
• Step into a method
– Inspecting variables
• These are automatically displayed
• Carefully develop a variety of test cases, then
static test
• Test the design (pseudocode) using the test cases
dynamic test
• executing the compiled program using the test cases
• Software is written by people – it is not perfect
• Testing is far more complex than running a program to see if it works
• Requires careful planning and discipline
• A program should be executed multiple times with various input in an attempt to find errors
• Document all test cases prior to testing including expected outputs
• Compare expected to actual outputs after testing
• eg to test an account code that is valid from 1 – 9999
• What data might you use?
Pseudocode revisited
What does a computer program do?
• Receive information
• Do something to the information
– Perform arithmetic
– Assign a value to a variable
– Compare 2 variables and select one of two alternative actions
– Repeat a group of actions
• Put out information
Receive information
When the information is being received from the keyboard we need to prompt the operator to enter the data
Prompt operator for studentName
• When a program is required to supply information to an output device, use Display, Print, or Write
• Display
– if the output is to be written to the screen
Display studentGrade
• For straightforward output it is sufficient to say
Display output as per specification
• Use either the mathematical symbols
total = total + number
• Or the words for those symbols
Add number to total
• Use Initialise, Set, =
Set assignmentMark to 0
Initialise customerCount to 0
totalPrice = costPrice + profitMargin
• Use IF for the condition
• Use ELSE for the false option
– use separate lines and indentation
• Use END to close the operation
IF (student is partTime)
add 1 to partTimeCount
ELSE
add 1 to fullTimeCount
END
• WHILE
– establishes the condition for the repetition of a group of statements (indented not using { })
• END
– closes the repeated statements
WHILE (patientID is valid)
finalPatientExpense = patientExpense + tax
Display finalPatientExpense
END
• Say we wanted to loop 12 times to collect monthly rainfall figures and accumulate them.
• The following pseudocode would be acceptable
For i = 1 to 12 loop
Prompt operator for month i rainfall
total = total + rainfall
END

--- More about jave
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: