Ⅰ. while 문
변수의 초기화;
while(조건식) {
조건식이 참(true)이라면 반복해서 실행할 명령문을 실행하고,
조건식이 거짓(false)이라면 while의 { } 이 부분을 빠져나간다.
반복해서 실행할 명령문;
증감식;
}
while문을 사용하여 Hello, Java! 를 5번 출력해 보자.
int cnt=5; // 5번 반복한다. (count)
int loop=0; // while문을 돌 때 반복 횟수
while(loop < cnt) {
System.out.println("Hello, Java!");
loop++;
}
변수 loop를 while문 안이 아니라 조건식에서 후위 증가를 할 때 결과를 생각해 보자.
int cnt=5; loop=0;
while(loop++ < cnt) {
// 0 < 5 ==> true, loop = 1
// 1 < 5 ==> true, loop = 2
// 2 < 5 ==> true, loop = 3
// 3 < 5 ==> true, loop = 4
// 4 < 5 ==> true, loop = 5
// 5 < 5 ==> false, 빠져나온다
System.out.println(loop+".안녕, 자바!");
}
변수 loop를 while문 안이 아니라 조건식에서 전위 증가를 할 때 결과를 생각해 보자.
int cnt=5; loop=0;
while(++loop < cnt) {
// 1 < 5 ==> true, loop = 1
// 2 < 5 ==> true, loop = 2
// 3 < 5 ==> true, loop = 3
// 4 < 5 ==> true, loop = 4
// 5 < 5 ==> false, 빠져나온다
System.out.println(loop+".안녕, 오라클!");
}
변수 loop를 while문 안 명령문에서 전위 증가를 할 때 결과를 생각해 보자.
int cnt=5; loop=0;
while(loop < cnt) {
System.out.println(++loop+".Hello, ORACLE!");
}
구구단 3단을 출력해 보자.
System.out.println("n=== 3단 ===");
int i=0, dan=3;
while(!(++i>9)) {
System.out.println(dan+"*"+i+"="+dan*i);
}
구구단 7단을 출력해 보자.
System.out.println("\n=== 7단 ===");
int i=0; dan=7;
while(true) {
i++;
if(i>9) break;
System.out.println(dan+"*"+i+"="+dan*i);
}
구구단 5단에서 홀수만 출력해 보자.
System.out.println("\n=== 5단 ===");
int i=0; dan=5;
while(true) {
i++;
if(i>9) break;
if(i%2==0) continue;
System.out.println(dan+"*"+i+"="+dan*i);
}
while()문을 사용하여 아래 결과가 나오는 구구단을 만들어 보자.
int row=0; // 행
int col=0; // 열
while(!(++row>9)) { // 9행
while(!(++col>8)) { // 8열
String str = ((col+1)<9)?"\t":"\n";
System.out.print((col+1)+"×"+row+"="+((col+1)*row)+str);
}
System.out.println("col ==> "+col);
}
-- 이렇게 코드를 짤 경우, 한 줄만 나타나고 멈춘다.
-- col 값을 밑에서 출력해 보면 이미 8이상이므로 while문을 실행하지 않기 때문에 col값을 초기화해 주어야 한다.
int row=0; // 행
int col=0; // 열
while(!(++row>9)) { // 9행
while(!(++col>8)) { // 8열
String str = (col+1<9)?"\t":"\n";
System.out.print((col+1)+"×"+row+"="+((col+1)*row)+str);
}
col=0;
}
while()문을 사용하여 아래 결과가 나오는 구구단을 만들어 보자.
int row=0; col=0;
while(!(++row>19)) { // 19행
while(!(++col>4)) { // 4열
if(row==10) {
System.out.println("");
break; // while문 빠져나가기
}
String str = "";
if(row<10) {
str = ((col+1)<5)?"\t":"\n";
System.out.print((col+1)+"×"+row+"="+((col+1)*row)+str);
}
else {
str = ((col+5)<9)?"\t":"\n";
System.out.print((col+5)+"×"+(row-10)+"="+((col+5)*(row-10))+str);
}
}
col=0;
}
Ⅱ. do while 문
변수초기화;
do{
반복해서 실행할 명령문;
증감식;
} while(조건식);
-- while 문의 경우 조건식이 true 일때만 반복 실행하지만, do ~ while 문의 경우는 조건식이 false 일지라도
무조건 do{ } 속에 있는 명령문은 1번은 실행하고서 반복문을 벗어난다.
-- do{ } 속에 있는 명령문을 실행하고서 while(조건식) 속의 조건에 따라 참(true)이라면 계속 반복하고, 조건이 거짓(false)이라면 중지한다.
do while문을 사용하여 안녕, 자바! 를 5번 출력해 보자.
▷첫 번째 방법
int i=0, cnt=5;
do {
i++;
System.out.println("Hello, Java!");
} while (i<cnt);
▷두 번째 방법
int i=0; cnt=5;
do {
System.out.println(++i+".Hello, Java!");
} while (!(i >= cnt));
do while()문을 사용하여 아래 결과가 나오도록 만들어 보자.
int svt=0, svtSum=0;
String resultStr = "";
do {
svt+=17; // svt = svt+17;
if(svt>100) break;
svtSum+=svt;
String comma = (svt>17)?", ":"";
resultStr += comma+svt;
} while (true);
System.out.println("1부터 100까지 중 17 배수는 "+resultStr);
System.out.println("1부터 100까지 중 17 배수들만의 합은 "+svtSum+"입니다");
입력 받은 시작 수(startNo)부터 끝 수(endNo)까지의 소수를 나타내 보자.
▷ 결과
-- startNo부터 endNo까지의 소수는?
-- startNo부터 endNo까지 소수의 개수는?
-- startNo부터 endNo까지 소수들의 합은?
Scanner sc = new Scanner(System.in);
int startNo=0, endNo=0;
do {
try {
System.out.print("▷ 시작 자연수 : ");
startNo = Integer.parseInt(sc.nextLine());
break;
}catch(NumberFormatException e) {
System.out.println("숫자만 입력 가능합니다. 다시 입력하세요.");
}
} while (true);
do {
try {
System.out.print("▷ 끝 자연수 : ");
endNo = Integer.parseInt(sc.nextLine());
break;
} catch (NumberFormatException e) {
System.out.println("숫자만 입력 가능합니다. 다시 입력하세요.");
}
} while (true);
System.out.println(startNo+"부터 "+endNo+"까지의 소수는? ");
sc.close();
문제 ▷▷ factorial을 나타내 보자.
import java.util.Scanner;
public class MainFactorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int facto=0, factoMul=1;
for(;;) {
try {
System.out.print(">> 알고 싶은 팩토리얼 수 입력 => ");
facto = Integer.parseInt(sc.nextLine());
break;
} catch(NumberFormatException e) {
System.out.println("정수만 입력하세요.");
}
}
String factoStr = "";
for(int i=facto; i>0; i--) {
factoStr += i+"*";
factoMul *=i;
}
System.out.println(facto+"!"+"="+factoStr.substring(0, factoStr.length()-1)
+"="+factoMul);
sc.close();
}
}
Ⅲ. Math.random
-- java.lang.Math.random() 메소드는 0.0 이상 1.0 미만의 실수(double)값을 랜덤하게 나타내어주는 메소드이다.
-- 0.0 <= 임의의 난수(실수) < 1.0
▷ 랜덤(1부터 10까지의 범위를 구한다. ==> 구간범위 : 10-1+1 = 10)
0.0 * 구간범위(10) ==> 0.0 (int)0.0 ==> 0 + 시작값(1) ==> 1
0.34 * 구간범위(10) ==> 3.4 (int)3.4 ==> 3 + 시작값(1) ==> 4
0.567 * 구간범위(10) ==> 5.67 (int)5.67 ==> 5 + 시작값(1) ==> 6
0.99999 * 구간범위(10) ==> 9.9999 (int)9.9999 ==> 9 + 시작값(1) ==> 10
-- 랜덤한 정수 = (int)(Math.random()*구간범위) + 시작값;
int rand1 = (int)(Math.random()*(10-1+1)) + 1;
System.out.println("1부터 10까지 중 랜덤하게 발생한 값 : " + rand1);
System.out.println("");
int rand2 = (int)(Math.random()*(18-13+1)) + 13;
System.out.println("13부터 18까지 중 랜덤하게 발생한 값 : " + rand2);
System.out.println("");
int rand3 = (int)(Math.random()*('z'-'a'+1)) + 'a';
System.out.println("a부터 z까지 중 랜덤하게 발생한 소문자 : " + (char)rand3);
Ⅳ. equals
-- 문자열 값을 비교해 준다.
String str1 = new String("이순신");
String str2 = new String("이순신");
System.out.println("str1 => " + str1);
System.out.println("str2 => " + str2);
if(str1==str2) {
System.out.println("str1과 str2는 같습니다.");
}
else {
System.out.println("str1과 str2는 같지 않습니다.");
}
-- 결과는 같지 않다고 나온다.
-- 문자열에서 "==" 비교 연산자는 메모리 주소를 비교하기 때문
-- 값을 비교하려면 equals를 사용해야 한다.
if(str1.equals(str2)) {
System.out.println("str1과 str2는 같습니다.");
}
else {
System.out.println("str1과 str2는 같지 않습니다.");
}
-- 소문자와 대문자를 비교하면 값이 같지 않다.
-- 소문자와 대문자를 구별하지 않고 비교하려면 equalsIgnoreCase를 사용하면 된다.
String str3 = "java";
String str4 = "jAva";
if(str3.equalsIgnoreCase(str4)) {
System.out.println("str3과 str4는 같습니다.");
} else {
System.out.println("str3과 str4는 같지 않습니다.");
}
가위바위보 게임 프로그램을 만들어 보자.
import java.util.Scanner;
public class MainGaiBaiBoGame {
public static void main(String[] args) {
int userNum=0;
Scanner sc = new Scanner(System.in);
do {
System.out.println("=========== 메뉴 ===========");
System.out.println("1.가위\t2.바위\t3.보\t4.게임종료");
System.out.println("===========================");
System.out.println(">> 선택하세요 => ");
try {
userNum = Integer.parseInt(sc.nextLine());
} catch(NumberFormatException e){
System.out.println("▷ 숫자로만 입력하세요.");
continue;
}
if(!(1 <= userNum && userNum <= 4)) {
System.out.println("▷ 메뉴에 존재하지 않는 번호입니다.");
continue;
}
if (1 <= userNum && userNum <= 3) {
System.out.print(">> 게임을 계속하시겠습니까?(Y/N) => ");
String yn = sc.nextLine();
if ("y".equalsIgnoreCase(yn))
continue;
else if ("n".equalsIgnoreCase(yn))
break;
else {
System.out.println("▷ 계속여부는 Y/N이어야 합니다.");
}
}
}
}
} while (!(userNum == 4));
sc.close();
System.out.println("=== 게임종료 ===");
}
}
▷ 기능 하나씩 설명
System.out.println("=========== 메뉴 ===========");
System.out.println("1.가위\t2.바위\t3.보\t4.게임종료");
System.out.println("===========================");
System.out.print(">> 선택하세요 => ");
-- 메뉴를 만든다.
int userNum=0;
try {
userNum = Integer.parseInt(sc.nextLine());
} catch(NumberFormatException e){
System.out.println("▷ 숫자로만 입력하세요.");
continue;
}
-- 1. 가위 / 2. 바위 / 3. 보 / 4. 게임종료를 숫자를 입력하여 선택하게 한다.
if(!(1 <= userNum && userNum <= 4)) {
System.out.println("▷ 메뉴에 존재하지 않는 번호입니다.");
continue;
}
-- 1~4 외 다른 숫자를 입력할 경우 "▷ 메뉴에 존재하지 않는 번호입니다." 를 출력하고 다시 선택하게 한다.
if (1 <= userNum && userNum <= 3) {
System.out.print(">> 게임을 계속하시겠습니까?(Y/N) => ");
String yn = sc.nextLine();
if ("y".equalsIgnoreCase(yn))
continue;
else if ("n".equalsIgnoreCase(yn))
break;
else {
System.out.println("▷ 계속여부는 Y/N이어야 합니다.");
}
}
-- 1~3 중 하나를 입력할 경우 ">> 게임을 계속하시겠습니까?(Y/N) =>" 을 선택하게 한다.
-- Y또는 y를 선택하면 메뉴를 다시 선택할 수 있고, N또는 n을 선택하면 게임이 종료된다.
while (!(userNum == 4));
-- 4를 입력할 경우 게임이 바로 종료된다.
문제 ▷▷ 게임을 계속하시겠습니까?(Y/N) 에서 Y(y)또는 N(n)을 입력하지 않고 다른 문자를 입력할 경우,
다시 게임을 계속하겠냐는 문구를 출력한다.
if (1 <= userNum && userNum <= 3) {
for (;;) {
System.out.print(">> 게임을 계속하시겠습니까?(Y/N) => ");
yn = sc.nextLine();
if (equalsIgnoreCase(yn)||"n".equalsIgnoreCase(yn))
break;
else {
System.out.println("▷ 계속여부는 Y/N이어야 합니다.");
continue;
}
}
}
if ("n".equalsIgnoreCase(yn))
break;
-- 반복문이 하나 더 생겼으므로 처음 for문에서 break를 걸어도 do while문에서 빠져나올 수 없어 종료가 되지 않는다.
-- 밑에 N(n)이 입력되면 break를 하는 if문을 한 번 더 써서 do while문에서 빠져나오도록 한다.