(ch3) - Loops, random numbers


while

while (Boolean) 
{
	statement_1
    statement_2
    
    statement_last
}
Scanner keyboard = new Scanner(System.in);
		System.out.println("put all your score and end with negative num");
		double next, sum = 0;
		int count = 0;
		next = keyboard.nextDouble();
		while (next >= 0)
		{
			sum += next; 
			count ++; 
			next = keyboard.nextDouble();
		}
		if (count == 0)
			System.out.println("no scoresm entered");
		else{
			double average = sum/count;
			System.out.println("average is " + average);
		}

do while syntax

do {
	statement1
    statement2
    
    statement last
} while (boolean);
int countDown; 
		System.out.println("First do while loop");
		countDown = 3;
		do {
			System.out.println("Hello World");
			countDown -- ; 
		} while (countDown > 0);

		System.out.println("second do while loop");
		countDown = 0;
		do{
			System.out.println("Hello World");
			countDown -- ; 
		} while (countDown > 0); //while문과 다르게 처음 한번은 무조건 실행
        
//First do while loop
Hello World
Hello World
Hello World
second do while loop
Hello World

for statement

for ( initialization; Boolean; update) 
	Body
for ( int number = 100; number >= 0; number --) 
	System.out.println(number + "bottles of beer ");]
    
// 100 bottles
99 bottles
...
0 bottles 

Nested Loops

int rowNum, columnNum;
		for (rowNum = 1; rowNum <= 3; rowNum++) {
			for (columnNum = 1; columnNum <= 3; columnNum++) {
				System.out.print(" row " + rowNum + " column " + columnNum);
			}
			System.out.println(); 
		}
//row 1 column 1 row 1 column 2 row 1 column 3
 row 2 column 1 row 2 column 2 row 2 column 3
 row 3 column 1 row 3 column 2 row 3 column 3

break


for (int i = 1; i <= 5; i++) {
			for (int j = 1; j <= 5; j++) {
				if (i == 3 && j == 3)
					break;
				System.out.print("(" + i + "," + j + ")");
			}
			System.out.println(); 
		}
        
//
(1,1)(1,2)(1,3)(1,4)(1,5)
(2,1)(2,2)(2,3)(2,4)(2,5)
(3,1)(3,2)
(4,1)(4,2)(4,3)(4,4)(4,5)
(5,1)(5,2)(5,3)(5,4)(5,5)

//제일 큰 loop에서 나오는게 아니라 가장 가까운 loop에서 빠져나옴

continue


for (int i = 1; i <= 10; i++) {
			if (i > 4 && i < 9) {
				continue;
			}
			System.out.println(i);
		}

//1
2
3
4
9
10

exit


プログラムを直接終了
まちがった面会
System.exit(0 );   // int

03-5 Random Numbers


擬似乱数:真のランダムではありませんbya seed value
same seed -> same sequence of random numbers
import java.util.Random; 
Random randomGenerator = new Random();
int r = randomGenerator.nextInt();

r = randomGenerator.nextInt(n); // 0,1,2,...,n-1 
r = randomGenerator.nextInt(3) + 4; // 0+4, 1+4, 2+4 
    
double rd = randomGenerator.nextDouble(); // 0.0 <= r < 1.0 
mathはimportを持たない
System.out.println(Math.random()); // [0.0 , 1.0)
for (int i = 0; i < 10; i++) {
      System.out.println((int)(Math.random()*6)+1); // int, [1, 6]
}