BackEnd/Backend 공부 정리
Java-7.2
by Brilliant_Graphite
2024. 8. 13.
package kr.co.hanuledu.controlex;
public class TestForIfex0 {
public static void main(String[] args) {
// 1 ~ 100 까지의 총합을(sum)을 구하시오.
// 단, 총합이 1024 이상이면 반복을 중지하고, 그때까지의 누적한 값을 출력하시오.
int i = 1;
int sum = 0;
while( i <= 100 ) {
sum += i;
if( sum >= 1024) {
break;
}
i++;
}
System.out.println("1에서 100까지의 총합은 " + sum + "입니다.");
System.out.println("반복한 횟수는 " + (i - 1) + "번 입니다.");
}
}
package kr.co.hanuledu.controlex;
import java.util.Scanner;
public class TestDiceGame {
public static void main(String[] args) {
/*
* 게임시작 1입력, 게임 종료 -1 "주사위를 굴려 볼까요?" 출력 사용자는 Enter Key를 입력 화면에 1 ~ 6 사이의 수중에서
* 무작위 하나의 수를 출력 "컴퓨터가 주사위를 굴려 볼까요?" 출력 사용자는 Enter Key를 입력 화면에 1 ~ 6 사이의 수중에서
* 무작위 하나의 수를 출력 사용자 수와 컴퓨터 수를 비교 -> 결과를 출력(Win, Lose, Draw)
*/
Scanner scanner = new Scanner(System.in);
boolean run = true;
while (run) {
System.out.println("게임을 시작하시겠습니까?");
System.out.println("시작 : 1입력 | 종료 : -1입력");
int num = scanner.nextInt();
scanner.nextLine(); // 버퍼를 비우기 위해 사용
if (num == 1) {
run = true;
} else if (num == -1) {
run = false;
System.out.println("게임 종료");
break;
}
System.out.print("주사위를 굴려 볼까요?");
scanner.nextLine();
int userDice = (int) (Math.random() * 6) + 1;
System.out.println("당신의 숫자는 " + userDice);
System.out.println();
System.out.print("컴퓨터가 주사위를 굴려 볼까요?");
scanner.nextLine();
int comDice = (int) (Math.random() * 6) + 1;
System.out.println("컴퓨터의 숫자는 " + comDice);
System.out.println();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (userDice > comDice) {
System.out.println("You Win!");
} else if (userDice == comDice) {
System.out.println("Draw");
} else if (userDice < comDice) {
System.out.println("You lose");
}
System.out.println();
System.out.println("==============");
}
}
}