Language/JAVA
[JAVA]가위바위보 게임 만들기(if문 활용)
영보로그
2020. 6. 22. 17:21
반응형
* 문제
사용자 입력 ==> 0,1,2 => 0이면 => 가위 => 1이면 => 바위 => 2이면 => 보 |
소스코드 1)
import java.util.Scanner;
public class 자바조건문문제3 {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("가위(0), 바위(1) 보(2) 입력 :");
int a = scan.nextInt();
if (a==0) {
System.out.println("Player : 가위");
}
if (a==1) {
System.out.println("Player : 바위");
}
if (a==2) {
System.out.println("Player : 보");
}
//컴퓨터
int com=(int)(Math.random()*3);
if(com==0)
{
System.out.println("컴퓨터 : 가위");
}
if(com==1)
{
System.out.println("컴퓨터 : 바위");
}
if(com==2)
{
System.out.println("컴퓨터 : 보");
}
//결과를 비교
/*
* 컴퓨터 : com
* 가위 => 0
* 사용자 : user
* 가위 => 0 => 0
* 바위 => 1 => -1
* 보 => 3 => -2
*
* 바위 => 1
* 사용자 :user
* 가위 => 0 =>1
* 바위 => 1 =>0
* 보 => 2 =>(-1)
*
* 보 => 2
* 사용자 : user -2,1
* 가위 => 0 =>(2) -1,2
* 바위 => 1 => 1
* 보 => 2 => 0
*/
//컴퓨터가 가위일 때
// ""문자열은 ==으로 비교가 불가능 => equals()
//중첩 조건문
if(com==0)
{
if(a==0)
{
System.out.println("비겼습니다.");
}
if(a==1)
{
System.out.println("Player 이김 ㅊㅊ");
}
if(a==2)
{
System.out.println("컴퓨터가 이김 ㅜㅜㅋ");
}
}
//컴퓨터가 바위일 때
if(com==1) {
if(a==0)
{
System.out.println("컴퓨터가 이김 ㅜㅜㅋ");
}
if(a==1)
{
System.out.println("비겼습니다.");
}
if(a==2)
{
System.out.println("Player 이김 ㅊㅊ");
}
}
//컴퓨터가 보 일때
if(com==2) {
if(a==0)
{
System.out.println("Player 이김 ㅊㅊ");
}
if(a==1)
{
System.out.println("컴퓨터가 이김 ㅜㅜㅋ");
}
if(a==2)
{
System.out.println("비겼습니다.");
}
}
}
소스 코드 2)
import java.util.Scanner;
public class 자바조건문문제3 {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("가위(0), 바위(1) 보(2) 입력 :");
int a = scan.nextInt();
if (a==0) {
System.out.println("Player : 가위");
}
if (a==1) {
System.out.println("Player : 바위");
}
if (a==2) {
System.out.println("Player : 보");
}
//컴퓨터
int com=(int)(Math.random()*3);
// =================
// 0.0~0.99*3==> 0.0~2.9... ==> 0~2
if(com==0)
{
System.out.println("컴퓨터 : 가위");
}
if(com==1)
{
System.out.println("컴퓨터 : 바위");
}
if(com==2)
{
System.out.println("컴퓨터 : 보");
}
//결과를 비교
/*
* 컴퓨터 : com
* 가위 => 0
* 사용자 : user
* 가위 => 0 => 0
* 바위 => 1 => -1
* 보 => 3 => -2
*
* 바위 => 1
* 사용자 :user
* 가위 => 0 =>1
* 바위 => 1 =>0
* 보 => 2 =>(-1)
*
* 보 => 2
* 사용자 : user -2,1
* 가위 => 0 =>(2) -1,2
* 바위 => 1 => 1
* 보 => 2 => 0
*/
if(com-a==-2 || com-a==1)
{
System.out.println("컴퓨터가 이김 ㅜㅜㅋ");
}
if(com-a==-1 || com-a==2)
{
System.out.println("Player 이김 ㅊㅊ");
}
if(com-a==0)
{
System.out.println("비겼습니다.");
}
}
}
- 주석의 사용자는 user인데 변수는 a를 활용하였습니다.
* 결과 화면
반응형