for๋ฌธ
- for๋ฌธ๋ด์ ์ด๊ธฐ์, ์กฐ๊ฑด์, ์ฆ๊ฐ์์ ๋ํ ์์ ๊ฐ์ง๊ณ ์๋ ์ ํ์ ๊ฐฏ์๋ฅผ ๋ฐ๋ณต ์ํํ ๋ ์ ์ฉํ๊ฒ ์ฌ์ฉ
- for๋ฌธ๋ด์ ์ด๊ธฐ์, ์กฐ๊ฑด์, ์ฆ๊ฐ์์ ๊ฐ๊ฐ ์๋ต ๊ฐ๋ฅ
- for๋ฌธ์์ ์คํ๋ ๋ช ๋ น๋ฌธ์ด ํ ์ค์ธ ๊ฒฝ์ฐ ์ค๊ดํธ ์๋ต ๊ฐ๋ฅ (์กฐ๊ฑด๋ฌธ๋ ๋์ผ)
๊ธฐ๋ณธ for๋ฌธ
public class ForEx1 {
public static void main(String[] args) {
for(int i = 1; i <= 100; i++) {
System.out.printf("%4d", i);
if(i % 10 == 0) System.out.println();
}
๊ตฌ๊ตฌ๋จ ์ฐ๊ธฐ
public class ForEx1 {
public static void main(String[] args) {
for (int i = 2; i < 10; i++) {
System.out.println("๊ตฌ๊ตฌ๋จ " + i + "๋จ");
for (int j = 1; j < 10; j++) {
System.out.printf("%d x %d = %d",i,j,(i*j));
System.out.println();
}System.out.println();
}
}
}
๋ณ ์ฐ๊ธฐ
public class ForEx1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("๋ณ ๊ฐฏ์ : ");
int star = sc.nextInt();
for(int i=0; i<star; i++) {
for(int j=0; j<star; j++) {
System.out.print("* ");
}System.out.println();
}
}
}
๋ณ ์ฐ๊ธฐ(2)
public static void main(String[]args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
for (int j = 0; j < i+1;j++) {
System.out.print("* ");
}
System.out.println();
}
}
* ๋ณ ์ฐ๊ธฐ ์ฐ์ต์ ์ฝ๋ฉ ์ฐ์ต ๊ฒ์ํ์์ ์ข ๋ ๋ค์ํ๊ฒ ๋ค๋ค ๋ณผ ์์ ์ด๋ค.
์ฌ๊ฐํ ์ฐ๊ธฐ
- ์์ ์ ์ n์ ๋ฐ์์ n * n ํฌ๊ธฐ์ ํ๋ ฌ์ ์ถ๋ ฅ
- ๊ฐ์ 1๋ถํฐ ์์
- ์ถ๋ ฅ ์์) ์ ์ ๊ฐ : 3
1 2 3
4 5 6
7 8 9
package For๋ฐ๋ณต๋ฌธ์ฐ์ต;
import java.util.Scanner;
public class ForEx1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("์ ์๋ฅผ ์
๋ ฅ ํ์ธ์. : ");
int num = sc.nextInt();
for(int i=1; i<=(num * num); i++) {
System.out.printf("%3d",i);
if(i % num == 0) System.out.println();
}
}
}
์ฃผ์ฌ์ ๊ฒ์
์ฃผ์ฌ์ 2๊ฐ ํฉ์ด 12๊ฐ ๋๋ฉด ํ์ถํ๋ ๊ฒ์
package ์ฃผ์ฌ์๊ฒ์;
public class DiceGameEx1 {
public static void main(String[] args) {
int dice1, dice2;
int count = 0;
while(true) {
count++;
dice1 = (int)(Math.random() * 6) + 1;
dice2 = (int)(Math.random() * 6) + 1;
System.out.println("์ฃผ์ฌ์์ ํฉ์ " + (dice1+dice2));
if((dice1 + dice2) == 12) break;
} System.out.println("ํ์ถ!");
System.out.printf("%d๋ฒ ์๋ ๋์ ํ์ถ ํ์์ต๋๋ค.",count);
}
}
* 1 ๋ถํฐ n ๊น์ง ๋๋ค ์ซ์ ์ถ๋ ฅ : (int)(Math.random() * n) + 1;
'๐๏ธ Backend > Java' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
์๋ฐ(Java) - ๋ฐฐ์ด๊ณผ ์ฐธ์กฐํ (1) ์ฐธ์กฐ ํ์ ๊ณผ ๋ฉ๋ชจ๋ฆฌ ๊ตฌ์กฐ (0) | 2023.01.07 |
---|---|
์๋ฐ(Java) - ํ์์ ๋ณด ์ถ๋ ฅํ๊ธฐ (2) | 2023.01.05 |
์๋ฐ(Java) - ์ ์ด๋ฌธ (2)์กฐ๊ฑด๋ฌธ(switch, while) + ์ค์ต์์ (1) | 2023.01.04 |
์๋ฐ(Java) - ์ ์ด๋ฌธ (1)์กฐ๊ฑด๋ฌธ(if, if~else, if~else if~else), ์ค์ต์์ (0) | 2023.01.03 |
์๋ฐ(Java) - ์ฐ์ฐ์ (0) | 2023.01.03 |