Enum 분석

Programing/Java 2016. 4. 11. 01:09 by kira-master

1.       Enum 이란 

 

 

 

 

2.       Enum 코드

public enum Operation {


   
PLUS("+") {
       
@Override
       
double apply(double x, double y) {
           
return x-y;
       
}

    }
, MINUS("-") {
       
@Override
       
double apply(double x, double y) {
           
return x-y;
       
}

    }
, TIMES("*") {
       
@Override
       
double apply(double x, double y) {
           
return x*y;
       
}

    }
, DIVIDE("/") {
       
@Override
       
double apply(double x, double y) {
           
return x/y;
       
}

    }
;

    private final
String symbol;

   
Operation(String symbol) {
       
this.symbol = symbol;
   
}

   
abstract double apply(double x, double y);

}

 

3.       Enum 바이트 코드 분석

 

 

Enum 클래스를 생성하게 되면 bytecode 시점에서는

enum 추상 클래스로 생성되면서 Enum 클래스의 상속을 받는다.

Enum 자료형은 모두 public static final enum Enum자료명으로 된다.

Static enum 형태로 내부 클래스로 선언된 되는데 밑에 보면 PlUS , MINUS, TIMES, DIVICE 라고 선언한


// class version 52.0 (52)
// access flags 0x4421
// signature Ljava/lang/Enum<Lcom/study/enum01/Operation;>;
// declaration: com/study/enum01/Operation extends java.lang.Enum<com.study.enum01.Operation>
public abstract enum com/study/enum01/Operation extends java/lang/Enum  {

// compiled from: Operation.java
// access flags 0x4008
static enum INNERCLASS com/study/enum01/Operation$4 null null
// access flags 0x4008
static enum INNERCLASS com/study/enum01/Operation$3 null null
// access flags 0x4008
static enum INNERCLASS com/study/enum01/Operation$2 null null
// access flags 0x4008
static enum INNERCLASS com/study/enum01/Operation$1 null null

// access flags 0x4019
public final static enum Lcom/study/enum01/Operation; PLUS

// access flags 0x4019
public final static enum Lcom/study/enum01/Operation; MINUS

// access flags 0x4019
public final static enum Lcom/study/enum01/Operation; TIMES

// access flags 0x4019
public final static enum Lcom/study/enum01/Operation; DIVIDE

// access flags 0x12
private final Ljava/lang/String; symbol

// access flags 0x101A
private final static synthetic [Lcom/study/enum01/Operation; $VALUES

// access flags 0x9
public static values()[Lcom/study/enum01/Operation;
       
L0
        LINENUMBER
6 L0
        GETSTATIC com/study/enum01/Operation.$VALUES : [Lcom/study/enum01/Operation
;
       
INVOKEVIRTUAL [Lcom/study/enum01/Operation;.clone ()Ljava/lang/Object;
       
CHECKCAST [Lcom/study/enum01/Operation;
       
ARETURN
        MAXSTACK =
1
       
MAXLOCALS = 0

// access flags 0x9
public static valueOf(Ljava/lang/String;)Lcom/study/enum01/Operation;
       
L0
        LINENUMBER
6 L0
        LDC Lcom/study/enum01/Operation
;.class
ALOAD 0
       
INVOKESTATIC java/lang/Enum.valueOf (Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;
       
CHECKCAST com/study/enum01/Operation
        ARETURN
        L1
        LOCALVARIABLE name Ljava/lang/String
; L0 L1 0
       
MAXSTACK = 2
       
MAXLOCALS = 1

// access flags 0x2
// signature (Ljava/lang/String;)V
// declaration: void <init>(java.lang.String)
private <init>(Ljava/lang/String;ILjava/lang/String;)V
        L0
        LINENUMBER
37 L0
        ALOAD
0
       
ALOAD 1
       
ILOAD 2
       
INVOKESPECIAL java/lang/Enum.<init> (Ljava/lang/String;I)V
        L1
        LINENUMBER
38 L1
        ALOAD
0
       
ALOAD 3
       
PUTFIELD com/study/enum01/Operation.symbol : Ljava/lang/String;
       
L2
        LINENUMBER
39 L2
        RETURN
        L3
        LOCALVARIABLE
this Lcom/study/enum01/Operation; L0 L3 0
       
LOCALVARIABLE symbol Ljava/lang/String; L0 L3 3
       
MAXSTACK = 3
       
MAXLOCALS = 4

// access flags 0x400
abstract apply(DD)D

       
// access flags 0x1000
       
synthetic <init>(Ljava/lang/String;ILjava/lang/String;Lcom/study/enum01/Operation$1;)V
        L0
        LINENUMBER
6 L0
        ALOAD
0
       
ALOAD 1
       
ILOAD 2
       
ALOAD 3
       
INVOKESPECIAL com/study/enum01/Operation.<init> (Ljava/lang/String;ILjava/lang/String;)V
        RETURN
        L1
        LOCALVARIABLE
this Lcom/study/enum01/Operation; L0 L1 0
       
LOCALVARIABLE x0 Ljava/lang/String; L0 L1 1
       
LOCALVARIABLE x1 I L0 L1 2
       
LOCALVARIABLE x2 Ljava/lang/String; L0 L1 3
       
LOCALVARIABLE x3 Lcom/study/enum01/Operation$1; L0 L1 4
       
MAXSTACK = 4
       
MAXLOCALS = 5

// access flags 0x8
static <clinit>()V
        L0
        LINENUMBER
9 L0
        NEW com/study/enum01/Operation$1
        DUP
        LDC
"PLUS"
       
ICONST_0
        LDC
"+"
       
INVOKESPECIAL com/study/enum01/Operation$1.<init> (Ljava/lang/String;ILjava/lang/String;)V
        PUTSTATIC com/study/enum01/Operation.PLUS : Lcom/study/enum01/Operation
;
       
L1
        LINENUMBER
15 L1
        NEW com/study/enum01/Operation$2
        DUP
        LDC
"MINUS"
       
ICONST_1
        LDC
"-"
       
INVOKESPECIAL com/study/enum01/Operation$2.<init> (Ljava/lang/String;ILjava/lang/String;)V
        PUTSTATIC com/study/enum01/Operation.MINUS : Lcom/study/enum01/Operation
;
       
L2
        LINENUMBER
21 L2
        NEW com/study/enum01/Operation$3
        DUP
        LDC
"TIMES"
       
ICONST_2
        LDC
"*"
       
INVOKESPECIAL com/study/enum01/Operation$3.<init> (Ljava/lang/String;ILjava/lang/String;)V
        PUTSTATIC com/study/enum01/Operation.TIMES : Lcom/study/enum01/Operation
;
       
L3
        LINENUMBER
27 L3
        NEW com/study/enum01/Operation$4
        DUP
        LDC
"DIVIDE"
       
ICONST_3
        LDC
"/"
       
INVOKESPECIAL com/study/enum01/Operation$4.<init> (Ljava/lang/String;ILjava/lang/String;)V
        PUTSTATIC com/study/enum01/Operation.DIVIDE : Lcom/study/enum01/Operation
;
       
L4
        LINENUMBER
6 L4
        ICONST_4
        ANEWARRAY com/study/enum01/Operation
        DUP
        ICONST_0
        GETSTATIC com/study/enum01/Operation.PLUS : Lcom/study/enum01/Operation
;
       
AASTORE
        DUP
        ICONST_1
        GETSTATIC com/study/enum01/Operation.MINUS : Lcom/study/enum01/Operation
;
       
AASTORE
        DUP
        ICONST_2
        GETSTATIC com/study/enum01/Operation.TIMES : Lcom/study/enum01/Operation
;
       
AASTORE
        DUP
        ICONST_3
        GETSTATIC com/study/enum01/Operation.DIVIDE : Lcom/study/enum01/Operation
;
       
AASTORE
        PUTSTATIC com/study/enum01/Operation.$VALUES : [Lcom/study/enum01/Operation
;
       
RETURN
        MAXSTACK =
5
       
MAXLOCALS = 0
       
}

 

 

 

 

'Programing > Java' 카테고리의 다른 글

자바 8 로 오면서 Runnable API 보던중에  (0) 2016.01.23
Connection 객체 // Properties  (0) 2015.09.09
계산기 예제  (0) 2015.08.27
POJO 의 개념과 예시  (0) 2015.08.24
Singleton 정리  (0) 2015.08.23

자바 8 로 오면서 Runnable API 보던중에

Programing/Java 2016. 1. 23. 23:16 by kira-master



자바 8로 오면서 Runnable 인터페이스 함수인터페이스 어노테이션이 선언되어 있었다.

모던 자바로 오면서 간결성을 좀더 추구하는 것 같다. 

'Programing > Java' 카테고리의 다른 글

Enum 분석  (0) 2016.04.11
Connection 객체 // Properties  (0) 2015.09.09
계산기 예제  (0) 2015.08.27
POJO 의 개념과 예시  (0) 2015.08.24
Singleton 정리  (0) 2015.08.23

Connection 객체 // Properties

Programing/Java 2015. 9. 9. 19:25 by kira-master


package exam;
// @author kosta, 2015. 9. 8 , 오후 7:53:23 , DB_Connection 
import java.io.FileReader;
import java.io.IOException;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DB_Connection_auto {
    private static Connection conn;
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    
    static {
        try {
            propertiesLoad(); // 설정값을 미리 로딩하고 
            Class.forName(driver);
            System.out.println("Log0 : 드라이버 로딩 완료");
            conn = DriverManager.getConnection(url,username,password);
            System.out.println("Log1 : Connection 객체 저장 완료 ");
            System.out.println("연결테스트 :"+conn);
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        } 
    }
    
    private DB_Connection_auto() {}
    public static Connection getConn() {
        return conn;
    }
    private static void propertiesLoad() {
        // The java.lang.Class.getResource() finds a resource with a given name
        // Class.getResource() 
        // 주어진 이름의 자원을 찾아내어 해당 클래스의 소스 파일 위치를 상대 경로에 따라서
        // 해당 자원의 URL 객체로 반환  
        // -> 해당 클래스의 상대경로에 있는 자원의 주소값을 가져옴 
        String path = DB_Connection_auto.class.getResource("jdbc.properties").getPath();
        System.out.println("Log Properties file Path :"+ path );
        
        Properties properties = new Properties();   
        try {
            path = URLDecoder.decode(path, "utf-8");
            // Properties 객체에 파일을 읽어와서 Driver 의 값을 가져옴 
            properties.load(new FileReader(path));   
            DB_Connection_auto.driver =  properties.getProperty("driver");
            DB_Connection_auto.url = properties.getProperty("url");
            DB_Connection_auto.username = properties.getProperty("username");
            DB_Connection_auto.password= properties.getProperty("password");
            } catch (IOException ex) {
                ex.printStackTrace();
        }
            
    } // end propertiesLoad()
} // end DB_Connection_auto();


// jdbc.properties
driver=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:xe
username=[id]
password=[password]


'Programing > Java' 카테고리의 다른 글

Enum 분석  (0) 2016.04.11
자바 8 로 오면서 Runnable API 보던중에  (0) 2016.01.23
계산기 예제  (0) 2015.08.27
POJO 의 개념과 예시  (0) 2015.08.24
Singleton 정리  (0) 2015.08.23

계산기 예제

Programing/Java 2015. 8. 27. 20:47 by kira-master


package exam;
// @author kosta, 2015. 8. 26 , 오후 6:12:23 , Calculator_ 
import java.util.Scanner;

public class Calculator_Main {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        Calculator calculator = new Calculator();
        
        
        System.out.println(" 계산기 프로그램 ");
        while (true) {            
            System.out.println("메뉴 사칙 연산 선택 +,-,/,* 중 하나를 입력하세요");    
            System.out.println("종료는 1 입니다.");
            String meun=sc.nextLine();
            if ("1".equals(meun)) {
                System.out.println("종료");
                return;
            }
            System.out.println("첫번쨰 숫자 입력  :");
            int n1 = Integer.parseInt(sc.nextLine());
            System.out.println("첫번쨰 숫자 입력  :");
            int n2 = Integer.parseInt(sc.nextLine());
            String res ="";
            switch(meun){
                case "+":
                    res  = calculator.plus(n1, n2);
                    System.out.println(res);
                    break;
                case "-":
                    res  = calculator.minus(n1, n2);
                    System.out.println(res);
                    break;
                case "/":
                    res  = calculator.divide(n1, n2);
                    System.out.println(res);
                    break;
                case "*":
                     res  = calculator.multiply(n1, n2);
                    System.out.println(res);
                    break;
                case "1":
                    System.out.println("종료");
                    return;
                default:
                    System.out.println("잘못된 입력입니다.");
                    break;
                    
            }
        }
        
        
        
    }
}





package exam;

// @author kosta, 2015. 8. 26 , 오후 6:04:23 , Calculator 
public class Calculator {
/*
필드 설계 하는법 
필드 클래스 내부에서 사용할 변수 선언 
또는 외부에서 들어온 매개변수의 값을 저장 
*/

/*
메소드 설계 하는법 
=>  기능(핵심) , 동작 중심의 실행을 염두한 구현 
*/    
    
    
public String plus(int n1,int n2){
    String str = "+ 연산의 ";
    int res = n1 + n2; 
    String result=result(res,str);
    return result;
}

public String minus(int n1,int n2){
    String str = "- 연산의 ";
    int res = n1 - n2; 
    String result=result(res,str);
    return result;
}

public String divide(int n1,int n2){
    String str = "/ 연산의 ";
    int res = n1 / n2; 
    String result=result(res,str);
    return result;
}

public String multiply(int n1,int n2){
    String str = "* 연산의 ";
    int res = n1 * n2; 
    String result=result(res,str);
    return result;
}

private String result(int res,String str){
    return str+" RESULT : " +res;
}
    
    
} // end class of Calculator


'Programing > Java' 카테고리의 다른 글

자바 8 로 오면서 Runnable API 보던중에  (0) 2016.01.23
Connection 객체 // Properties  (0) 2015.09.09
POJO 의 개념과 예시  (0) 2015.08.24
Singleton 정리  (0) 2015.08.23
자바 메모리 구조 2  (0) 2015.08.22

POJO 의 개념과 예시

Programing/Java 2015. 8. 24. 21:09 by kira-master


package exam;
// POJO 의 개념 
// 1. 상속받지 않는 클래스이다.
// 2. 외부로부터 생성자에 의해서 필드값이 변경되지 않는다.
// 3. 내부의 필드는 getter and setter 의해서만 변경된다.
// 4. 필드는 모두 Priavate 처리 
// @author kosta, 2015. 8. 24 , 오전 10:46:01 , ExamMember 
public class ExamMember {
    private String name;
    private int age;
    private boolean agree;

    public ExamMember() {}

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public boolean getAgree() {
        return agree;
    }

    public void setAgree(boolean agree) {
        this.agree = agree;
    }
 } // end class of ExamMember



'Programing > Java' 카테고리의 다른 글

Connection 객체 // Properties  (0) 2015.09.09
계산기 예제  (0) 2015.08.27
Singleton 정리  (0) 2015.08.23
자바 메모리 구조 2  (0) 2015.08.22
String 객체 특징 (== 연산자 특징)  (0) 2015.08.22

Singleton 정리

Programing/Java 2015. 8. 23. 12:29 by kira-master


package com.lec.java.singleton;
// Java Singleton Pattern
// 1. 내부에 자기 자신의 하나의  인스턴스만 생성해서 사용하다.
// 2. 외부의 생성자 접근을 막는다.
// 3. 오로지 클래스 내부에서만 객체를 관리한다.
public class Singleton {
	private static Singleton Instance; 
	private  Singleton() {}
	
	private static Singleton getInstance() {
		if (Instance== null) {
			Instance = new Singleton();
		}
		return Instance;
	}
	
} // end class of Singleton



package com.lec.java.singleton;
// 스레드의 동기화 문제 때문에 메소드 자체에 synchronized를 붙어줌 
// 이렇식으로 싱글턴을 구현하면 속도가 크게 저하될수있음 
// 동시에 여러개의 쓰레드가 이 객체를 사용하면 느려질수 밖에 없음 
public class Singleton_MutiThread {
	private static Singleton_MutiThread Instance;
	
	private Singleton_MutiThread() {}
	
	private static synchronized Singleton_MutiThread getInstance() {
		if (Instance==null) {
			Instance = new Singleton_MutiThread();
		}
		return Instance;
	}
} // end class of Singleton_MutiThread


package com.lec.java.singleton;
// 동시에 쓰레드에서 동기화 할때 두개 이상 생성되는 것을 막는 방법 
public class Singleton_MutiThread_Sychronized {
	private static volatile Singleton_MutiThread_Sychronized Instance; 
	// volatile : CPU 캐쉬가 아닌 실제 메모리부터 적재하여 사용하는 방법 
	
	private Singleton_MutiThread_Sychronized() {}
	
	private static Singleton_MutiThread_Sychronized getInstance() {
		if (Instance == null) { // 동시에 
			synchronized (Singleton_MutiThread.class) {			
				if (Instance==null) {
					Instance = new Singleton_MutiThread_Sychronized();
				}

			}

		}
				return Instance;
	}
} // end class of Singleton_MutiThread_Sychronized


'Programing > Java' 카테고리의 다른 글

계산기 예제  (0) 2015.08.27
POJO 의 개념과 예시  (0) 2015.08.24
자바 메모리 구조 2  (0) 2015.08.22
String 객체 특징 (== 연산자 특징)  (0) 2015.08.22
자바 메모리 구조1. 변수의 저장영역  (0) 2015.08.22

자바 메모리 구조 2

Programing/Java 2015. 8. 22. 11:49 by kira-master

참고 공부 자료 http://performeister.tistory.com/75

package com.lec.java;

public class Myclass {
	private int a;
	private int b;
	
	public Myclass(){}
	
	public static void result(){
		System.out.println("myclass 입니다.");
	}
	
} // Myclass  


package com.lec.java;

public class Intance {
	public static void main(String[] args) {
		Myclass m1 = new Myclass();
		Myclass m2 = new Myclass();
		System.out.println("m1 == m2 "+(m1 == m2)); // false 
		System.out.println();
		System.out.println("m1 : "+m1);
		System.out.println("m2 : "+m2);
		System.out.println();
		System.out.println("m1 해쉬 코드 :" +m1.hashCode());
		System.out.println("m2 해쉬 코드 :" +m2.hashCode());
		
	}// end main
} // end class



결과값 
// m1 == m2 false

// m1 : com.lec.java.Myclass@659e0bfd
// m2 : com.lec.java.Myclass@2a139a55

// m1 해쉬 코드 :1704856573
// m2 해쉬 코드 :705927765
// 레퍼런스 변수에는 객체 대한 참조값이 들어간다. 어떤 JVM 영역의 힙 영역 중  어떤 메모리 주소를 가르킬지를 참고하는 것이다.
// 객체는 생성 될떄마다 항상 새로운 힙의 주소를 가지고 , 만약에 더이상 참조 되지 않으면 힙에서 가비지 컬렉터가 메모리를 반환시켜버리고 
// 다시 생성하여도 항상 다른 힙에 대한 주소를 가질수 밖에 없다.


'Programing > Java' 카테고리의 다른 글

POJO 의 개념과 예시  (0) 2015.08.24
Singleton 정리  (0) 2015.08.23
String 객체 특징 (== 연산자 특징)  (0) 2015.08.22
자바 메모리 구조1. 변수의 저장영역  (0) 2015.08.22
홀짝 게임 예제  (0) 2015.08.21

String 객체 특징 (== 연산자 특징)

Programing/Java 2015. 8. 22. 11:31 by kira-master


package com.lec.java;

public class String01 {
	public static void main(String[] args) {
		String a = "Hello"; // String 문자열을 "" 식으로 대입 연산자로 대입 시키면 
		String b = "Hello"; // Stirng 문자열은 상수풀에 저장되어 버린다.
		System.out.println(a==b)
                // == 연산자는 reference 변수의 참조값을 비교함 // 상수풀에 복사되어 같은 곳을 바라봄  
		//result => true
		System.out.println(a.hashCode());
		System.out.println(b.hashCode());
		// 두 객체의 해시코드 값은 같다. 
		
		String a2 = new String("Java");
		String b2 = new String("Java");
		System.out.println(a2==b2); // new 연산자를 사용하여 생성하면 다른 객체로 두개 생성
		// result => false
		System.out.println(a2.hashCode());
		System.out.println(b2.hashCode());
		 
		
		// 유의점 
		//hashCode값 출력(문자열값이 같으므로 같은 hashCode)
		//스트링 키객체의 주소가 달라도 같은 값을 가지면 객체의 해쉬 코드는 같다
		//String 클래스에 hashCode()메소드가 오버라이딩 되있기 때문에           
		//키 객체의 값이 같을때 이와 같이 같은 헤쉬코드를 리턴해야 
               //해쉬테이블, 해쉬맵 사용시 제대로된 Key로써 역할을 하기에 오버라이딩함
		
		// 본인 설명 추가++ 
		// 원래 Object의 Class 의  hashCode() 메소드랑은 메소드 내부가 다르게 정의됨 .
		// 그래서 String 객체는 다른 일반적인 객체들과 달리 같은 문자열이 같으면 해쉬코드도 같음 
		
		/* => 결과값 
		 * true
		   69609650
                   69609650
                   false
                   2301506
		   2301506
		 * 
		 */
		
	}
} // end class 



'Programing > Java' 카테고리의 다른 글

Singleton 정리  (0) 2015.08.23
자바 메모리 구조 2  (0) 2015.08.22
자바 메모리 구조1. 변수의 저장영역  (0) 2015.08.22
홀짝 게임 예제  (0) 2015.08.21
1일차 Subnote  (0) 2015.08.17

자바 메모리 구조1. 변수의 저장영역

Programing/Java 2015. 8. 22. 10:29 by kira-master


public class MemoryArchitecture {
	// ======================== Field ===============================================================
	int n1 = 10; 		           // Member Variable(Intance Variable) => 클래스를 생성할때 힙에 올라가는 변수  
	String s1=  "Hello";		   // Member Variable(Intance Variable)
	static int n2= 10;  		   // Class Variable     // => class 변수들은 JVM 의 
	static String s2= "Java"; 	   // Class Variable     // Method 영역에서 클래스가 로드될떄 같이 생성  
	static final int n3= 20;       // final로 선언하면 Class Variable은  상수로 치환되어 Constant Pool 복사 
	static final String s3= "C++"; // final로 선언하면 Class Variable은  상수로 치환되어 Constant Pool 복사 
	
	// ======================== 메소드 내부 안은 로컬 영역 ===============================================
	public static void t1(int a) { // parameter Variable
		int a1; // local Variable 
		int b2; // local Variable
	}// end main
	
} // end class 

자바는 변수들이 Runtime 시점시에 자바 메모리에 크게 

stack 영역 - local Variable , Parameter Variable
class(Methoed) 영역 - Class Variable (static Variable)

heap 영역 -Member Variable(Instance Variable) 


위 구조로 메모리 영역에 들어갑니다.

흔히 필드라고 불리는 곳은 class에서  메소드 내부 안이 아니라 클래스의 내부에서 선언한 

멤버 변수 , 클래스 변수라고 합니다.


Class 변수(Static 변수로)는 class 파일을 실행할 때 JVM의 클래스 영역에서 이미 메모리를 할당되어서 

JVM에 꺼질떄까지 계속 메모리에 상주합니다. 

 

Member 변수(Class 변수는)는 MemoryArchitecture의타입으로 객체가 생성될때 같이 메모리에 올라가서 

참조가 끊길떄까지 계속 메모리에 올라갑니다.  ->가비지 컬렉터가 메모리를 수거하기 전까지 메모리에 올라감


Static final 로 선언한 Class Variable은 JVM의 Class 영역 중에 상수풀로 복사되어서 계속 메모리에 상주합니다.

=> final 로 선언하면 한번 초기화하면 다시 초기화가 불가능합니다.

'Programing > Java' 카테고리의 다른 글

자바 메모리 구조 2  (0) 2015.08.22
String 객체 특징 (== 연산자 특징)  (0) 2015.08.22
홀짝 게임 예제  (0) 2015.08.21
1일차 Subnote  (0) 2015.08.17
1. Variable  (0) 2015.08.15

홀짝 게임 예제

Programing/Java 2015. 8. 21. 20:31 by kira-master



예제 홀짝 게임 





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package exam;
// @author kosta, 2015. 8. 20 , 오후 2:31:41 , ExamGame 
import java.util.Scanner;
/*
홀 / 짝 게임 
사용자가 입력한 숫자(1,2)가 CPU 가 발생시킨 변수가 
일치할 경우 You win , 아니면 You lose 를 출력하고
사용자가 종료를 눌렀을 때 게임 결과와 경품결과를 출력한다.
*/
public class Exam_OddNumber_EvenNumber_Game {
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        int total = 0// 총 실행한 게임수
        int winConut=0// 총 이긴 횟수 
        
        // ========================= 사용자 메뉴 UI ========================== 
        exit:while (true
        {
            System.out.println(" 1. 홀 2. 짝 3. 종료 ");
            int num = Integer.parseInt(sc.nextLine()); // 사용자로부터 입력
            boolean res=false;
            switch(num)
            {
                case 1:
                    System.out.println("홀을 선택했습니다.");  
                    ++total;
                    res=outCome(num);
                    if(res){
                        System.out.println("You win");
                        ++winConut;
                    }else {
                        System.out.println("You lose");
                    }
                    break;
                case 2:
                    System.out.println("짝을 선택했습니다."); 
                    ++total;
                     res =outCome(num);
                     if(res){
                        System.out.println("You win");
                        ++winConut;
                    }else {
                        System.out.println("You lose");
                    }
                    break;
                case 3:
                    displayResult(total,winConut);
                    break exit;
            } // end swich
        } // end while 
    } // end main
    
// ============================= 메소드 선언부  ===============================
    
    /**
     * 총 게임 횟수와 총 이긴횟수를 파라미터로 받아서
     * 게임의 결과를 출력하는 메소드
     * @param total // 총 게임횟수
     * @param winConut // 총 이긴 횟수 
     */
    private static  void displayResult(int total, int winConut){
        // 결과 출력창 
        System.out.println("Total : "+ total);
        System.out.println("WIN SCORE : "+winConut);
        System.out.println("LOSE SCORE :"+(total-winConut));
        System.out.println("승률 :"+(int)(((float)winConut/(float)total)*100)+"%");
        prizeResult(winConut); // => 상품 결과 추가 출력 
    } // end displayResult()
    
    /**
     * 획득한 점수에 따라서 상품에 대한 결과를 출력하는 메소드
     * @param winConut // 총 이긴 횟수 
     * dispaly() 메소드로부터 호출 받아서 
     */
    private static void prizeResult(int winConut)
    {
        if (winConut>=90
        {
            System.out.println("상품 A ");
        }else if (winConut>=80) {
            System.out.println("상품 B ");
        }else if (winConut>=70) {
            System.out.println("상품 C ");
        }else if (winConut<=60){
            System.out.println("상품 X ");
        }
        System.out.println("종료 합니다.");
    } // end prizeResult()
    
    /**
     * 랜덤의 값을 발생시켜 홀수 짝수의 따른 일치여부로 승패 결과를
     * 처리해주는 메소드 
     * 난수 발생 범위 :(1<= Random <11)
     * @param num 사용자가 선택한 홀 / 짝을 파라미터로 받음 
     * @return 사용자의 승패를 결과에 따른 결과를 반환
     */
    private static boolean outCome(int num)
    {
          boolean res=false;
          int cpuNum=(int) ((Math.random()*10+ 1); 
          System.out.println("CPU 난수: "+ cpuNum);
          if(num==1) res=cpuNum%2!=0// 홀수  
          if(num==2)res=cpuNum%2==0// 짝수  
        return res;
    } // end outCome()
    
// end class 
 
cs












'Programing > Java' 카테고리의 다른 글

자바 메모리 구조 2  (0) 2015.08.22
String 객체 특징 (== 연산자 특징)  (0) 2015.08.22
자바 메모리 구조1. 변수의 저장영역  (0) 2015.08.22
1일차 Subnote  (0) 2015.08.17
1. Variable  (0) 2015.08.15
Nav