열심히 끝까지
Java1 day03 보충 본문
package example01;
import java.util.Scanner;
public class FlowEx12{
public static void main(String[] args){
// 입력한 숫자를 모두 더함, 단 0을 입력하는 순간 덧셈을 멈춤.
Scanner sc = new Scanner(System.in);
int num = 0;
int sum = 0;
boolean flag = true;
while(flag {
System.out.print("합계를 구할 숫자를 입력하세요(종료 : 0) > ");
num = sc.nextInt();
// 1번째 방법
if(num == 0){
break;
}
sum += num;
// 2번째 방법
if(num != 0) {
sum += num;
}else {
flag = false;
}
}
System.out.println("누적합 : " + sum);
}
}
package example01;
import java.util.Scanner;
public class FlowEx13{
public static void main(String[] args){
// do-while문
// Math.random() : 난수 변환(랜덤숫자뽑기)
/*
* Math.random();
* 0.0 <= Math.random() < 1.0 ==> 각 항에 100을 곱하기
* 0.0 <= Math.random() <100.0 ==> (int)로 형변환
* 0 <= Math.random() <100 ==> 각 항에 1 더하기
* 1 <= Math.random() < 101
*/
int input = 0;
int answer = (int)(Math.random() * 100) + 1 // 1 ~ 100까지의 랜덤한 정수 반환
Scanner sc = new Scanner (System.in);
System.out.println("answer : " + answer);
do {
System.out.print("1과 100 사이의 정수를 입력하세요 > ");
input = sc.nextInt();
if(input < answer) {
System.out.println("더 큰수로 시도해보세요");
} else if(input > answer) {
System.out.println("더 작은 수로 시도해보세요");
}
}while(input != answer);
System.out.println("정답!");
}
}
//continue 예시
package example01;
public class FlowEx14 {
public static void main(String[] args){
//continue
for(int i = 1; i <= 10; i++) {
if(i % 3 == 0) {
continue; // 조건문 숫자만 제외하고 계속 진행
}
System.out.println(i); // 1 2 4 5 7 8 10
}
System.out.println();
for(int i = 1; i <= 10; i++) {
if(i == 5) {
break; // 반복문 자체를 깨부수는 것
}
System.out.println(i); // 1 2 3 4
}
System.out.println();
for(int i = 0; i <= 10; i++) {
for(int j = 0; j <= 10; j++) {
if( j == 5 ) {
break;
}
System.out.println(" " + j); // 0 1 2 3 4
}
if(i == 3) {
break;
}
System.out.println();
System.out.println("i : " + i); // 0 1 2
}
}
}
'Java1(주말)' 카테고리의 다른 글
Java1 day04 보충 (0) | 2022.04.23 |
---|---|
Java1 day04 (0) | 2022.04.17 |
Java1 day03 (0) | 2022.04.16 |
Java1 day02 보충 2 (0) | 2022.04.16 |
Java1 day02 보충 1 (0) | 2022.04.12 |