문제1) 1부터 10까지 정수 중에서 짝수인 것만 출력해주세요
public class Practice {
public static void main(String[] args) {
int i=1; //시작은 1부터
while(i<=10) {왜?while반복문?? 얼만큼 반복할지 모르기 때문에
if(i%2=0) {
Sysout.println("i");
}
i++
}
}
문제2) 1부터 10까지 출력해주세요
public class Practice {
public static void main(String[] args) {
int i=1;
while(i<=10) {
System.out.println(i);
}
i++;
}
}
문제3) 10부터 1까지 출력해주세요
public class Practice {
public static void main(String[] args) {
int i=10; //10부터 시작하는 i
while(i>=1) { //i가 1일 될때까지
System.out.println(i);
}
i--; //i를 1씩 감소시키면서
}
}
문제4) 1에서 10까지의 정수들 중에서 10의 약수인 정수들만 출력해주세요
public class Practice {
public static void main(String[] args) {
int i=1;
while(i<=10) {
if(10%i==0) {//10을 i로 나눴을 때, 0이 되는 i
System.out.println(i);
}
i++;
}
}
}
문제5) 1부터 100까지의 정수들을 모두 더해가면서 그 총합을 출력해주세요
단, 총합이 50을 초과하면 총합을 그만 출력해주세요
public class Practice {
public static void main(String[] args) {
int i=1;
int total=0;
while(i<=100) {
i++;
total+=i;
if(total>50) {
break;
}
System.out.println(total);
}
}
}
심화) 별찍기
★
★ ★
★ ★ ★
★ ★ ★ ★
★ ★ ★ ★ ★
이 문제를 풀려면 디버깅표를 그려야 한다
1.마지막 줄은 5개의 별
한개씩 늘려가면서 별을 찍어보자.
2. while(i<5)
i=0부터 시작
print와 println 주의!
public class Practice {
public static void main(String[] args) {
int i=0;
while(i<5) {
int j=0;
while( j<=i ) {
System.out.print("★");
j++;
}
System.out.println();
i++;
}
}
}
i | j | j<=i |
0 | 0 | t |
1 | 0 | t |
1 | t | |
2 | 0 | t |
1 | t | |
2 | t | |
3 (x) | f | |
3 | 0 | t |
1 | t | |
2 | t | |
3 | t |
i
'JAVA > 코드' 카테고리의 다른 글
강의 4일차 문제 풀기 (0) | 2025.01.30 |
---|---|
강의 3일차 문제풀기- 반복문 (0) | 2025.01.30 |
강의 2일차 문제풀기- 조건문 (0) | 2025.01.29 |
과제 2번 - Thread 와 동기화 (0) | 2025.01.22 |
과제 1번 - 입출력(IO)을 이용한 업다운 게임 (0) | 2025.01.21 |