2012.10.26. for loop while loop do while loop how to choose? nested loop practice

15
JAVA 2012.10.26

Upload: buck-thomas

Post on 17-Dec-2015

237 views

Category:

Documents


4 download

TRANSCRIPT

JAVA2012.10.26

OUTLINE for loop while loop do while loop How to choose? Nested loop practice

FOR 迴圈 (LOOP)

迴圈內的動作

進入迴圈

true

false

離開迴圈

迴圈條件運算式

for ( i=1 ; i<=100 ; i++ ) //迴圈條件運算式{

//迴圈內的動作 ;}

FOR 迴圈 (LOOP)

WHILE LOOP EX:

int count=0;while ( count<100 ){

System.out.println(”Hello!”);count++;

}

loop-continuatio

n condition?

Statement(s)(loop body)

false

true

count=0

(count < 100) ?

System.out.println(“Hello!”);count++;

DO WHILE LOOP EX:

int count=0;do {

System.out.println(”Hello!”);count++;

} while ( count<100 );

loop-continuatio

n condition?

Statement(s)(loop body)

false

true

count=0

(count < 100) ?

System.out.println(“Hello!”);count++;

PRETEST & POSTTEST LOOP 先測迴圈 : while、 for

The condition is checked before the loop body is excuted.

後測迴圈 : do while

The condition is checked after the loop body is excuted.

HOW TO CHOOSE?A for loop may be used if the number of

repetitions is known in advance.

A while loop may be used if the number of repetitions is not fixed.

A do while loop can be used to replace a while loop if the loop body has to be executed before the condition is tested.

NESTED(巢狀 ) LOOPfor

{

…….

for

{

…….

}

}

PRACTICE 1.寫一個程式,計算 1-100可被 3整除的數值總和

2.Create modified versions of the Stars program to print the following pattern. Create a separate program to produce each patten.並且讓使用者可以輸入 stars的高 .

PRACTICE 3.Design and implement an application that plays the

Rock-Paper-Scissors game against the computer. When played between two people, each person picks on of three options at the same time, and a winner is determined. In the game, Rock beats Scissors, Scissors beats Paper, and Paper beats Rock. The program should randomly chosse on of the three options(without revealing it), then prompt for the user’s selection. At that point, the program reveals both choices and prints a statement indicating if the user won, the computer won, or if it was a tie. Continue playing until the user chooses to stop, then print the number of user wins, losses, and ties.

Ppt下載: http://oss.csie.fju.edu.tw/~jastine01/

ppt.html

RANDOM NUMBERimport java.util.Scanner;

public class SubtractionQuiz{

public static void main(String[] args){

int number1=(int)(Math.random()*10);

int number2=(int)(Math.random()*10);

if(number1<number2){

int temp =number1;

number1=number2;

number2=temp;

System.out.print("What is "+number1+" - "+number2+" ? ");

Scanner input= new Scanner(System.in);

int answer =input.nextInt();

if(number1-number2==answer){

System.out.println("You are correct!!");

}else{

System.out.println("Your answer is wrong\n"+number1+"-"+number2+"is"+(number1-number2));

}

}

}

}