Sie sind auf Seite 1von 74

TCC 101 Computing I

Tutorial 3

Prepared by : Ng Mee Mee


Learning Objectives
 Discover how to create a Java Program
 Learn how to compile and run the java
program
 Explore how to document a program
using comments
 Learn how to import packages and why
they are necessary
 Examine ways to input data using dialog
box
Learning Objectives (cont)
 Examine ways to output results using
output statements and message dialog
box.
 Learn about control structures
 Sequence (if statement)
 Branching (if..else, switch/case, conditional
operator)
 Looping (while, do..while, for loop)
 Examine relational and logical operators
 Examine break and continue statements
Creating a Java
Application Program
 Syntax of a class:

 Syntax of the main method:


A Simple Application
//This application program prints
Welcome to Java!

public class Welcome {


public static void main(String[]
args) {
System.out.println("Welcome to
Java!");
}
}
Two Ways to Create Java
Program
 Create a class with a main method to execute
the program
 For example, ComputeNumber.java

 You need to compile & run

ComputeNumber.java to output the


results
 one java file created

 Create a class and use a driver program to


execute the program
 For example, ComputeNumber.java,

TestComputeNumber.java
 You need to compile these two files and run

TestComputeNumber.java to output the


results

ComputeNumber class
ComputeNumb
public class ComputeNumber{ er class contain
public static void main(String[] args){ main method
int number1= 20;
int number2 = 2;
int total;

total = number1 + number2;

System.out.println("The total for "


+ number1 + " + " + number2 + " is "
+ total);

}
ComputeNumber class
/**
* @(#)ComputeNumber.java ComputeNumber
*
class contain the
*
* @ng mee mee method named
* @version 1.00 2007/3/24 addNumber which
*/
accept two integer
values
public class ComputeNumber{

public int addNumber(int n1, int n2){

return n1 + n2;

}
}
/**
* @(#)TestComputeNumber.java
* The class definition of TestComputeNumber for setting
up the
* environment and test the ComputeNumber object
* @ng mee mee
* @version 1.00 2007/3/24 A driver program for
*/
ComputeNumber
public class TestComputeNumber{ named
TestComputeNumber
// the main execute method
public static void main(String[] args){
// create the ComputeNumber object
ComputeNumber compute = new
ComputeNumber();

//Sending messages with numbers to the object so


that
//the numbers are added
int total = compute.addNumber(10,2);

//display the result to the screen


System.out.println("The total =" + total);
Comments

Used to document what the program is


and how the program is constructed.
In Java, comments are preceded by two

slashes (//) in a line, or enclosed between


/* and */ in one or multiple lines.
 When the compiler sees //, it ignores all

text after // in the same line.


When it sees /*, it scans for the next */

and ignores any text between /* and */.


Example of Comments

// This application program prints


welcome to java!

/*This application program prints


welcome to java! */

/*This application program


prints welcome to java! */
import Statement

 Used to import the components of a


package into a program.
 Reserved word.
 import javax.swing.*;
Imports the (components of the)
package javax.swing.* into the
program.
 Primitive data types and the class
String:
 Part of the Java language.
Example: Import
Statement
import javax.swing.*;

public class ImportDemo {

public static void main(String[] args) {


String
string=JOptionPane.showInputDialog(null,"Prompt
Message",
"Dialog
Title",JOptionPane.QUESTION_MESSAGE);

}
}
Getting Input from Input Dialog
Boxes
String string = JOptionPane.showInputDialog(
null, “Prompt Message”, “Dialog Title”,
JOptionPane.QUESTION_MESSAGE));
Displaying text in console
 What is System.out.println?
 System.out is known as the standard
output object, println is a method in the
object
 It is a collection of statements that
performs a sequence of operations to
display a message on the console.
 Example:
System.out.println("The total =" + total);
Displaying Text in a Message
Dialog Box

you can use the


showMessageDialog method in the
JOptionPane class.
JOptionPane is one of the many

predefined classes in the Java


system, which can be reused
rather than “reinventing the
wheel.”
The
showMessageDialog
Method
JOptionPane.showMessageDialog(null, "Welcome 
to Java!",  "Example 1.2", 
JOptionPane.INFORMATION_MESSAGE));
Converting Strings to Integers

The input returned from the input dialog box is


a string. If you enter a numeric value such as
123, it returns “123”. To obtain the input as a
number, you have to convert a string into a
number.

To convert a string into an int value, you can


use the static parseInt method in the Integer
class as follows:

int intValue = Integer.parseInt(intString);



Converting Strings to Doubles

To convert a string into a double value, you


can use the static parseDouble method in the
Double class as follows:

double doubleValue
=Double.parseDouble(doubleString);

where doubleString is a numeric string such


as “123.45”.
Example: Converting Strings to Integers
& display results on message dialog box
-
-
ComputeNumber compute = new ComputeNumber();

//get the number from the user using dialog box


String s1 = JOptionPane.showInputDialog("Input first
number");
//Convert string value into integer value
int n1 = Integer.parseInt(s1);

String s2 = JOptionPane.showInputDialog("Input second


number");
//Convert string value into integer value
int n2 = Integer.parseInt(s2);

//Sending messages with numbers to the object so that


//the numbers are added
int total = compute.addNumber(n1,n2);

//display the result to message dialog box


JOptionPane.showMessageDialog(null, " The total is " +
Control Structures
Comparison Operators
•Java provides six comparison operators that can be used to compare two
value.
•The result of the comparison is a Boolean value : true or false.
Operator Name Example
Answer
< less than 1<2 true
<= less than or equal to 1<= 2 true
> greater than 1>2 false
>= greater than or equal to 1>= 2 false
== equal to 1= = 2 false
!= not equal to 1 != 2 true
Example: Comparison
Operator
public class Double
{
public static void main(String[] args)
{
int i = 1;
//if-else statement
if( i == 2)
System.out.println("i equals 2");
else
System.out.println("i does not equal 2");

}
}
Boolean Operators
Boolean operators also known as logical operators.
A variable that holds a Boolean value is known as a
Boolean variable. i.e. boolean lightsOn = true;
Operator Name Description
! not logical negation
&& and logical conjunction
|| or logical disjunction
^ exclusive or logical exclusion
Truth Table for Operator !

Operand !Operand Example


true false !(1>2) is true
false true !(1>0) is false

The not (!|) operators negates true to false and


false to true.
Truth Table for Operator
&&
P1 p2 p1 && p2 Example
false false false (2>3) &&(5>5) is false
false true false
true false false (3>2) &&(5>5) is false
true true true (3>2)&&(5>=5) is true

The and (&&|) of two Boolean operands is true if and


only if both operators is true.
Truth Table for Operator ||

p1 p2 p1 || p2 Example
false false false (2>3) || (5>5) is false
false true true
true false true (3>2) || (5>5) is true
true true true

The or (||) of two Boolean operands is true if at least


one of the operators is true.
Truth Table for Operator ^
p1 p2 p1 ^ p2 Example
false false false
false true true (2>3) ^(5>1) is true
true false true
true true false (3>2) ^(5>1) is false

The exclusive or (^) of two Boolean operands is true


if and only if the two operands have different
Boolean values.
Example: Boolean Operators
public class RelationalLogicalOperators
{
public static void main(String args[])
{
// Demonstration of relational and logical operators
boolean aBoolean = true;
boolean anotherBoolean = false;

System.out.println(aBoolean || anotherBoolean);
System.out.println(aBoolean && anotherBoolean);
System.out.println(!aBoolean);

int anInt = 5;
int anotherInt = 6;

// Note that relational expressions return boolean values


System.out.println(anInt < anotherInt);
System.out.println(anInt == anotherInt);
System.out.println(anInt != anotherInt);
}
}
Selection Statements
 Java has several types of selection
statements:
 simple if statements
 if...else statements
 Nested if statements
 switch statements
 Conditional expressions
Simple if Statements
 A simple if statement executes an action only if the
condition is true
 Syntax
The condition must be a boolean expressio
if is a Java It must evaluate to either true or false.
reserved word

if ( condition )
statement;

If the condition is true, the statement is executed.


If it is false, the statement is skipped.
Logic of if statements

condition
evaluated

true false

statement

An if statement executes statements if the condition evaluated as


true
Example: Simple if
Statements
public class simpleIf{
public static void main(String[] args){
int i=3;

if ((i>0) && (i<10)) {


System.out.println("i is an
integer between 0 and 10");
}
} Braces can be omitted if
the block contains a single
} statement
The if...else Statement
 An else clause can be added to an if
statement to make 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
Logic of an if...else
statements
condition
evaluated

true false

statement1 statement2

An if…else statement executes statements for the true case if the


condition evaluated as true; otherwise statements for the false case are
executed
Example: if...else statement
public class ComputeArea{
public static void main(String[] args){
final double PI = 3.145;
double radius = -3;
double area;

if (radius >= 0) {
area = radius*radius*PI;
System.out.println("The area for the circle of radius " + ra
+
" is " + area);
}
else {
System.out.println("Negative input");
}
}
Nested if statements
 The statement executed as a result of an
if statement or else clause could be
another if statement
 These are called nested if statements
 An else clause is matched to the last
unmatched if (no matter what the
indentation implies)
 Braces can be used to specify the if
statement to which an else clause
Example: Nested if
statement
int i = 1; int j = 2; int k = 3;
if(i>k){
if(j>k)
System.out.println("i and j are greater than
k");
}
else
System.out.println("i is less than or equal to k");
}
The if (j>k) statement is nested inside the if (i>k)
statement
Multiple Alternative if
Statements
if (score >= 90) if (score >= 90)
grade = ‘A’; grade = ‘A’;
else else if (score >= 80)
if (score >= 80)
grade = ‘B’;
grade = ‘B’;
else else if (score >= 70)
if (score >= 70) grade = ‘C’;
grade = ‘C’; else if (score >= 60)
else
grade = ‘D’;
if (score >= 60)
grade = ‘D’; else
else grade = ‘F’;
grade = ‘F’;

This is better
switch Statements
 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 associated with the first
switch Statements
 The general syntax of a switch
statement is:
switch switch ( expression )
and {
case case value1 :
are statement-list1
reserve case value2 :
d statement-list2 If expression
words case value3 : matches value2,
statement-list3 control jumps
case ... to here

}
switch Statements
 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 can be appropriate, but
usually we want to execute only the
statements associated with one case
switch Statements
 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
 Though the default case can be positioned
anywhere in the switch, usually it is placed at
the end
 If there is no default case, and no other value
matches, control falls through to the
Example: switch
statements
public class SwitchDemo {
public static void main(String[] args) {
int month = 8;
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
}
}
Conditional Operator
 Java has a conditional operator that
evaluates a boolean condition that
determines which of two other expressions
is evaluated
 The result of the chosen expression is the
result of the entire conditional operator
 Its syntax is:
condition ? expression1 :
expression2


Conditional Operator (cont)
 The conditional operator is similar to an if-
else statement, except that it forms an
expression that returns a value
 For example:
larger = ((num1 > num2) ? num1 :
num2);
 If num1 is greater that num2, then num1 is
assigned to larger; otherwise, num2 is
assigned to larger
 The conditional operator is ternary
because it requires three operands
Conditional Operator
if (x > 0)
y = 1;
else
y = -1;

is equivalent to

y = (x > 0) ? 1 : -1;
Example: Conditional
Operator
public class TestConditional{
public static void main(String[] args){
int num=20;
if (num % 2 == 0)
System.out.println(num + " is even");
else
System.out.println(num + " is odd");

System.out.println((num % 2 == 0)? num + " is even":


num + "is odd");

}
}
Loop Statements
 The while Loops
 The do-while Loops
 The for Loops
 break and continue
The while Loop
 The while statement has the following
syntax:
while ( condition )
while is a
statement;
reserved word

If the condition is true, the statement is executed


Then the condition is evaluated again.

The statement is executed repeatedly until


the condition becomes false.
Logic of a while loop

condition
evaluated

true false

statement

The while loop repeatedly executes the statements in the


loop body /statement when the condition evaluated as true.
Example: a while
i = 0;
Loop

int i = 0; (i < 100)


false
while (i < 100) {
System.out.println(
"Welcome to true
Java!"); System.out.println("Welcoem to Java!");
i++;
i++;
}
Next
Statement
The do-while Loop
Syntax:
do
do and {
while are statement;
reserved }
words while ( condition )

The statement is executed once initially,


and then the condition is evaluated

The statement is executed repeatedly


until the condition becomes false
Logic of a do-while Loop

•A do loop is similar to a
while loop, except that the
statement
condition is evaluated
after the body of the loop true
is executed condition
•Therefore the body of a evaluated

do loop will execute at false


least once
Example: the do-while Loop
import javax.swing.JOptionPane;
public class TestDoWhile{
public static void main(String[] args){
int data;
int sum=0;
do
{
String dataString=JOptionPane.showInputDialog(null,
"Enter an int value, \nthe program exits if the input is 0",
"TestDo", JOptionPane.QUESTION_MESSAGE);

data = Integer.parseInt(dataString);
sum+=data;
}while(data !=0);

JOptionPane.showMessageDialog(null,"the sum is" + sum,


"TestDo", JOptionPane.INFORMATION_MESSAGE);
}
}
The for Loop
 syntax:
The initialization The statement is
Reserved
is executed once executed until the
word
before the loop begins
condition becomes false

for ( initialization ; condition ; increment )


statement;

The increment portion is executed at the end of each iteration


The condition-statement-increment cycle is executed repeatedl
The for Loop
 A for loop is functionally equivalent to
the following while loop structure:
initialization;
while ( condition )
{
statement;
increment;
}

for ( initialization ; condition ; increment )


statement;
Logic of a for loop
initialization

condition
evaluated

true false

statement

increment

A for loop performs an initial action once, then repeatedly executes


the statements in the loop body, and performs an action after an
increment when the condition evaluated as true
The for loop
 Like a while loop, the condition of a for
statement is tested prior to executing the
loop body
 Therefore, the body of a for loop will
execute zero or more times
 It is well suited for executing a loop a
specific number of times that can be
determined in advance
Example: a while loop & a for Loops

Example: A while loop


int i = 0;
while (i < 100) {
System.out.println("Welcome to Java! ”
+ i);
i++;
}
Example: a for loop
int i;
for (i = 0; i < 100; i++) {
System.out.println("Welcome to Java! ”
+ i);
for Loop Example
i=0

int i; false
i++ i<100?
for (i = 0; i<100;
i++) { true
System.out.println( System.out.println(
"Welcome to “Welcom to Java!”);
Java");
}

Next
Statement
Which Loop to Use?
A for loop may be used if the number of
repetitions is known, as, for example, when
you need to print a message 100 times.
A while loop may be used if the number of
repetitions is not known, as in the case of
reading the numbers until the input is 0.
A do-while loop can be used to replace a
while loop if the loop body has to be executed
before testing the continuation condition.
The break Keyword

• Break
immediately ends
the innermost
loop that contains
it.
• Generally used
with an if
statement
Example: break keyword
public class TestBreak{
public static void main(String[] args)
{
int sum=0;
int number=0;
while(number < 20){
number++;
sum+=number;
if(sum>=100)break;
}
System.out.println("The number is " +
number);
System.out.println("The sum is " + sum);
}
The continue Keyword

•Continue only ends


the current iteration.
• Program control
goes to the end of
the loop body.
•Generally used with
an if statement
Example: Continue
Keyword
public class TestContinue{
public static void main(String[] args)
{
int sum=0;
int number=0;
while(number < 20){
number++;
if(number ==10 || number
==11)continue;
sum+=number;
}
System.out.println("The sum is " + sum);
}
TMA 3 ~Question 1
Solution:
2. Prompt the user to enter any integer number
below 20. (Use dialog box to get input from
users)
3. Convert the number (e.g., 18) in string value
into integer value.
4. Validate the integer number. The integer
number must less than 20 and greater than -1.
So the acceptable range for input integer
number is 0-19.
5. Return e to the power value of input integer
number
6. Display appropriate message to user if an
invalid integer number is entered such as -5,
20, or 26.
Study Guide for Question 1
 Course materials
 Unit 3, section 3.3, 3.5
 Unit 4 Control Structures
 Unit 4 References section on page 95
 Focus on the use of while, do while, break,
continue, if..else
 Text Book
 Chapter 4 & 5
 Tutorial 3 slides
Study Guide for Question
1(cont)
 The Math Class
 http://en.wikibooks.org/wiki/Java_Program
 http://java.sun.com/docs/books/tutori
al/java/data/beyondmath.html
 http://java.sun.com/j2se/1.5.0/docs/ap
i/java/lang/Math.html
TMA 3 ~Question 2
Solution:
2. Prompt the user to enter the amount
as strings such as 255, 268. (Use
dialog box to get input from users)
3. Convert the amount (e.g., 255) in
string value into integer value.
4. Divide the cents by 100 to find the
number of dollars. Obtain the
remaining cents using the cents
remainder 100.
5. Divide the remaining cents by 25 to
find the number of quarters. Obtain
the remaining cents using the
TMA 3 ~Question 2 (cont)
1. Divide the remaining cents by 10 to
find the number of dimes. Obtain the
remaining cents using the remaining
cents remainder 10.
2. Divide the remaining cents by 5 to find
the number of nickels. Obtain the
remaining cents using the remaining
cents remainder 5.
3. The remaining cents are pennies.
4. Display the result either through
console or message dialog box.
Study Guide for Question 2
 Text Book
 chapter 2 & 3
 Focus on arithmetic operators,
especially the use of % modulus
operators (page 36-39)
 Tutorial3 slides
TMA 3 ~Question 3
 3a) fill in missing code
 3b) complete the method
distanceTravelled()
 3c) write a driver program named
TurtleTester to test on Turtle class

Das könnte Ihnen auch gefallen