res/layout/activity.xml

<RelativeLayout
    android:id="@+id/btn_layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true" >

    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal" >

        <RadioButton
            android:id="@+id/bt1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="a" />

        <RadioButton
            android:id="@+id/bt2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="b" />

        <RadioButton
            android:id="@+id/bt3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="c" />

        <RadioButton
            android:id="@+id/bt4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="d" />
    </RadioGroup>
</RelativeLayout>


각종 타입 변환하기

byte _byte = 12;
int _int = 123;
long _long = 12;
float _float = 1.23f;
double _double = 123.123;
String str;

// Byte <-> String
str = Byte.toString(_byte);
_byte = Byte.parseByte(str);
				
// Integer <-> String
str = Integer.toString(_int);
_int = Integer.parseInt(str);
				
// Long <-> String
str = Long.toString(_long);
_long = Long.parseLong(str);
				
// Float <-> String
str = Float.toString(_float);
_float = Float.parseFloat(str);
				
// Double <-> String
str = Double.toString(_double);
_double = Double.parseDouble(str);;



'대학 생활 > JAVA' 카테고리의 다른 글

[JAVA] java.io.File 클래스  (0) 2014.04.10
[JAVA]정적필드, 정적메소드  (0) 2014.03.18
[JAVA] heap, stack 메모리  (0) 2014.01.24
[JAVA] ArrayList, LinkedList, Stack, Queue  (0) 2014.01.09

heap - 객체가 저장되는 곳(garbage collector 있음)

stack - 메소드 호출과 지역변수가 저장되는 곳

instance variable - 클래스 내에서 선언한 변수

local variable - 메소드 안에서 선언한 변수


지역변수도 저장된 객체는 변수만 스택에 저장



'대학 생활 > JAVA' 카테고리의 다른 글

[JAVA]정적필드, 정적메소드  (0) 2014.03.18
[JAVA] String <-> int, double, float 변환  (0) 2014.02.28
[JAVA] ArrayList, LinkedList, Stack, Queue  (0) 2014.01.09
[JAVA] 계산기  (0) 2014.01.05
package DataStructure_Test;

import java.util.*;

class ArrayListTest {
	public static void main(String[] args) {
		// ArrayList
		ArrayList<integer> var1 = new ArrayList<integer>();
		var1.add(1);
		var1.add(2);
		var1.add(3);
		var1.add(0, 4);
		for (int i = 0; i < var1.size(); i++) {
			System.out.println(var1.get(i).intValue());
		}

		// LinkedList
		LinkedList<string> var2 = new LinkedList<string>();
		var2.add("str1");
		var2.add("str2");
		var2.add("str3");
		for (int i = 0; i < var2.size(); i++) {
			System.out.println(var2.get(i).toString());
		}

		// Stack
		LinkedList<string> stack1 = new LinkedList<string>();
		stack1.push("stack1");
		stack1.push("stack2");
		stack1.push("stack3");
		while (!stack1.isEmpty()) {
			System.out.println(stack1.pop());
		}

		// Queue
		LinkedList<string> queue1 = new LinkedList<string>();
		queue1.offer("queue1");
		queue1.offer("queue2");
		queue1.offer("queue3");
		while (!queue1.isEmpty()) {
			System.out.println(queue1.poll());
			// System.out.println(queue1.peek());
			// peek() 메서드는 가져오기만 하므로 무한루프
		}
	}
}

'대학 생활 > JAVA' 카테고리의 다른 글

[JAVA] String <-> int, double, float 변환  (0) 2014.02.28
[JAVA] heap, stack 메모리  (0) 2014.01.24
[JAVA] 계산기  (0) 2014.01.05
[JAVA] 은행 통장 입출금 예제  (2) 2014.01.05
import java.awt.*;
import java.awt.event.ActionListener;

import javax.swing.*;

class MainClass{
	public static void main(String[] args) {
		
		// window 창 설정
		JFrame frame = new JFrame("simple calculator");
		frame.setLocation(500, 400);
		frame.setPreferredSize(new Dimension(300, 200));
		Container contentPane = frame.getContentPane();

		JTextField resultField = new JTextField();
		contentPane.add(resultField, BorderLayout.NORTH);

		GridLayout button_layout = new GridLayout(4, 4);
		JPanel panel_button = new JPanel();
		panel_button.setLayout(button_layout);

		
		JButton[] nums = new JButton[10];
		nums[0] = new JButton("0");
		nums[1] = new JButton("1");
		nums[2] = new JButton("2");
		nums[3] = new JButton("3");
		nums[4] = new JButton("4");
		nums[5] = new JButton("5");
		nums[6] = new JButton("6");
		nums[7] = new JButton("7");
		nums[8] = new JButton("8");
		nums[9] = new JButton("9");
		
		JButton clr = new JButton("C"); // clear
		JButton equals = new JButton("="); // result
		JButton add = new JButton("+");
		JButton sub = new JButton("-");
		JButton mul = new JButton("*");
		JButton div = new JButton("/");

		panel_button.add(nums[7]);
		panel_button.add(nums[8]);
		panel_button.add(nums[9]);
		panel_button.add(add);
		panel_button.add(nums[4]);
		panel_button.add(nums[5]);
		panel_button.add(nums[6]);
		panel_button.add(sub);
		panel_button.add(nums[1]);
		panel_button.add(nums[2]);
		panel_button.add(nums[3]);
		panel_button.add(mul);
		panel_button.add(nums[0]);
		panel_button.add(equals);
		panel_button.add(clr);
		panel_button.add(div);

		contentPane.add(panel_button, BorderLayout.CENTER);

		// event
		
		ActionListener numberPressListener = new NumberButtonListener(resultField);
		for(int i = 0; i < 10; i++) {
			nums[i].addActionListener(numberPressListener);
		}

		clr.addActionListener(numberPressListener);
		equals.addActionListener(numberPressListener);
		add.addActionListener(numberPressListener);
		sub.addActionListener(numberPressListener);
		mul.addActionListener(numberPressListener);
		div.addActionListener(numberPressListener);
		
		// window 띄우기
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

class NumberButtonListener implements ActionListener {
	JButton btn;
	JTextField result;

	private int total = 0;
	private char op = ' ';

	NumberButtonListener(JTextField result) {
		this.result = result;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String getBut = e.getActionCommand();
		String presentVal = result.getText();

		if (getBut == "0") {
			if(!presentVal.equals("0")) {
				result.setText(presentVal + getBut);
			}
		} else if (getBut == "1") {
			result.setText(presentVal + getBut);
		} else if (getBut == "2") {
			result.setText(presentVal + getBut);
		} else if (getBut == "3") {
			result.setText(presentVal + getBut);
		} else if (getBut == "4") {
			result.setText(presentVal + getBut);
		} else if (getBut == "5") {
			result.setText(presentVal + getBut);
		} else if (getBut == "6") {
			result.setText(presentVal + getBut);
		} else if (getBut == "7") {
			result.setText(presentVal + getBut);
		} else if (getBut == "8") {
			result.setText(presentVal + getBut);
		} else if (getBut == "9") {
			result.setText(presentVal + getBut);
		} else if (getBut == "C") {
			result.setText("");
			total = 0;
		} else if (getBut == "+") {
			int temp =  Integer.parseInt(presentVal);
			switch (op) {
			case '+':
				total += temp;
				break;
			case '-':
				total -= temp;
				break;
			case '*':
				total *= temp;
				break;
			case '/':
				total /= temp;
				break;
			default:
				total = temp;
			}
			op = '+';
			result.setText("");
		} else if (getBut == "-") {
			int temp =  Integer.parseInt(presentVal);
			switch (op) {
			case '+':
				total += temp;
				break;
			case '-':
				total -= temp;
				break;
			case '*':
				total *= temp;
				break;
			case '/':
				total /= temp;
				break;
			default:
				total = temp;
			}
			op = '-';
			result.setText("");
		} else if (getBut == "*") {
			int temp =  Integer.parseInt(presentVal);
			switch (op) {
			case '+':
				total += temp;
				break;
			case '-':
				total -= temp;
				break;
			case '*':
				total *= temp;
				break;
			case '/':
				total /= temp;
				break;
			default:
				total = temp;
			}
			op = '*';
			result.setText("");
		} else if (getBut == "/") {
			int temp =  Integer.parseInt(presentVal);
//			total = total / Integer.parseInt(presentVal);
			switch (op) {
			case '+':
				total += temp;
				break;
			case '-':
				total -= temp;
				break;
			case '*':
				total *= temp;
				break;
			case '/':
				total /= temp;
				break;
			default:
				total = temp;
			}
			op = '/';
			result.setText("");
		} else if (getBut == "=") {
			int temp = Integer.parseInt(presentVal);
			switch (op) {
			case '+':
				total += temp;
				break;
			case '-':
				total -= temp;
				break;
			case '*':
				total *= temp;
				break;
			case '/':
				total /= temp;
				break;
			default:
				total = temp;
			}
			op = ' ';
			result.setText("" + total);
			System.out.println(total);
		}
	}

}
MainClass.java
public class MainClass {
	public static void main(String[] args) {

		basicFunc start = new basicFunc();
		start.play();
	}
}
BasicFunc.java
import java.util.Scanner;

class BasicFunc {
	void play() {
		String name;
		String accountNo;
		int limit;
		System.out.println("사용자메뉴");
		Scanner in = new Scanner(System.in);
		loop: while (true) {
			System.out.println("1. 일반 통장 개설");
			System.out.println("2. 마이너스 통장 개설");
			System.out.println("3. 종료");
			System.out.print("->");
			int chk = in.nextInt();
//			try {
				in.nextLine();
				switch (chk) {
				case 1:
					System.out.println("일반 통장 개설");
					System.out.print("이름 : ");
					name = in.nextLine();
					System.out.print("계좌번호 : ");
					accountNo = in.nextLine();
					System.out.println(name + ", " + accountNo);
					try{
					Account person = new Account(name, accountNo);
					person.play();
					}catch(Exception e) {
						System.out.println(e.getMessage());
					}
				
					
					
					break;
				case 2:
					System.out.println("마이너스 일반 통장 개설");
					System.out.print("이름 : ");
					name = in.nextLine();
					System.out.print("계좌번호 : ");
					accountNo = in.nextLine();
					System.out.print("한도 : ");
					limit = in.nextInt();
//					Account personM = new AccountM(name, accountNo, limit);
//					personM.play();
					break;
				case 3:
					break loop;
				default:
					System.out.println("다시 입력해주세요.");

				}
//			} catch (Exception e) {
//				System.out.println(e.getMessage());
//			}
		}
		System.out.println("system quit..");
	}
}
Account.java
import java.util.Scanner;

public class Account {
	String name; // 예금주 이름
	String accountNo; // 계좌번호
	int balance; // 잔고

	// 생성자
	Account() {
	}

	Account(String name, String accountNo) throws Exception {
		if(name.equals("\n") || accountNo.equals(null)) {
			System.out.println("값 없음");
			throw new Exception("값을 모두 입력하세요.");
		}
		this.name = name;
		this.accountNo = accountNo;
	}

	// ----------------------
	// 생성자 끝

	void play() {
		Scanner in = new Scanner(System.in);
//		System.out.print("이름 : ");
//		this.name = in.nextLine();
//		System.out.print("계좌번호 : ");
//		this.accountNo = in.nextLine();
		int temp;
		int chk = 1;
		loop: while (chk != 0) {
			try {
				System.out.println("1. 입금, 2. 출금, 3. 정보, 0. 종료");
				System.out.print("->");
				int num = in.nextInt();
				switch (num) {
				case 1:
					System.out.print("입금얼마?");
					temp = in.nextInt();
					inputMoney(temp);
					break;
				case 2:
					System.out.print("출금얼마?");
					temp = in.nextInt();
					outputMoney(temp);
					break;
				case 3:
					infoPrint();
					break;
				case 0:
					break loop;
				default:
					System.out.println("다시입력하시오");
				}

			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
		}
	}

	void infoPrint() {
		System.out.println("이름 : " + name);
		System.out.println("게좌 : " + accountNo);
		System.out.println("잔액 : " + balance);
	}

	void inputMoney(int amount) {
		this.balance += amount;
		System.out.println(amount + "원을 입금하고, 잔액은 " + balance + "원입니다.");
	}

	void outputMoney(int amount) throws Exception {
		if (balance < amount) {
			throw new Exception("잔액이 부족합니다.");
		} else {
			balance -= amount;
			System.out.println(amount + "원을 인출하고, 잔액은 " + balance + "원입니다.");
		}
	}

	void calculateInterest() {

	}
}
AccountM.java
import java.util.Scanner;

public class AccountM extends Account {
	int limit = 0; // 마이너스 한도

	// 생성자
	AccountM() {
		// 기본 한도 500만원.
		this.limit = 500;
	}

	AccountM(String name, String accountNo, int limit) throws Exception {
		super(name, accountNo);
		this.limit = limit;
	}

	// ----------------------
	// 생성자 끝

	void play() {
		Scanner in = new Scanner(System.in);
		System.out.print("이름 : ");
		this.name = in.nextLine();
		System.out.print("계좌번호 : ");
		this.accountNo = in.nextLine();
		System.out.print("한도 : ");
		this.limit = in.nextInt();
		int temp;
		int chk = 1;
		loop: while (chk != 0) {
			try {
				System.out.println("1. 입금, 2. 출금, 3. 정보, 0. 종료");
				System.out.print("->");
				int num = in.nextInt();
				switch (num) {
				case 1:
					System.out.print("얼마?");
					temp = in.nextInt();
					inputMoney(temp);
					break;
				case 2:
					System.out.print("얼마?");
					temp = in.nextInt();
					outputMoney(temp);
					break;
				case 3:
					infoPrint();
					break;
				case 0:
					break loop;
				default:
					System.out.println("다시입력하시오");
				}

			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
		}
	}

	// 오버라이딩
	void infoPrint() {
		System.out.println("이름1 : " + name);
		System.out.println("게좌 : " + accountNo);
		System.out.println("한도금액 : " + limit);
		System.out.println("잔고 : " + balance);
		System.out.println("인출가능잔액 : " + (balance + limit));
	}

	void inputMoney(int amount) {
		this.balance += amount;
		System.out.println(amount + "원을 입금하고, 잔액은 " + (balance + limit)
				+ "원입니다.");
	}

	// 오버라이딩
	void outputMoney(int amount) throws Exception {
		if ((balance + limit) < amount) {
			throw new Exception("잔액이 부족합니다.");
		} else {
			balance -= amount;
			System.out.println(amount + "원을 인출하고, 인출가능잔액은 " + (balance + limit)
					+ "원입니다.");
		}
	}
}


'대학 생활 > JAVA' 카테고리의 다른 글

[JAVA] ArrayList, LinkedList, Stack, Queue  (0) 2014.01.09
[JAVA] 계산기  (0) 2014.01.05
[JAVA] * 별 출력하기_10 다이아몬드  (0) 2013.11.15
[JAVA] * 별 출력하기_09 마름모  (0) 2013.11.14

* 별 출력하기_10 다이아몬드


public class Star {

	public static void main(String args[]) {

		int input = 5;
		int st = 0;
		input = (input % 2 == 0) ? input - 1 : input;
		st = input/2;
		
		for (int line = 0; line < input; line++) {
			for (int put = 0; put < (input - st); put++) {
				System.out.print((put >= st) ? "*" : " ");
			}
			st = line < (input / 2) ? st - 1 : st + 1;
			System.out.println();
		}
	}
}


'대학 생활 > JAVA' 카테고리의 다른 글

[JAVA] 계산기  (0) 2014.01.05
[JAVA] 은행 통장 입출금 예제  (2) 2014.01.05
[JAVA] * 별 출력하기_09 마름모  (0) 2013.11.14
[JAVA] 스무고개 만들기  (0) 2013.10.28
※ 메인메서드아닙니다.
void shape(int size) {
		// 3보다 큰 수 홀수 입력받아야하고, 잘못받으면 계속 입력받아야 한다.
		int mid = size / 2 + 1;
		int star = mid;
		for(int line = 1, blank = (size/2); line <= size; line++) {
			for(int colum = 1; colum <= star; colum++) {
				System.out.print(blank >= colum ? " " : "*");
			}
			System.out.printf("\t\t\t star : %d, blank : %d\n", star, blank);
			star = ((line < mid) ? star+1 : star-1);
			blank = ((line >= mid) ? blank+1 : blank-1);
		}
	}
import java.util.Random;
import java.util.Scanner;

public class Smugogae {
	public static void main(String[] args) {
		Random ran = new Random();
		Scanner in = new Scanner(System.in);
		int val = ran.nextInt(20) + 1;
		int input;
		int cnt = 0;

		System.out.println("답:" + val);

		System.out.println("스무고개(1~20)");
		do {
			System.out.print("input : ");
			input = in.nextInt();
			if (val > input) {
				System.out.printf("%d보다 큽니다.\n", input);
			} else if (val < input) {
				System.out.printf("%d보다 작습니다.\n", input);
			}
			cnt++;
			System.out.println("count " + cnt);
		} while (input != val && cnt < 20);

		if (cnt > 20) {
			System.out.println("val = " + val);
			System.out.println("20번이 넘었습니다.");
		} else {
			System.out.println("val = " + val);
			System.out.println("count = " + cnt);
		}
	}
}
앞 포스팅과 다른점은 try-catch 위치 변경.
package Test03;


class MainClass {
	public static void main(String[] args) {
		// 객체 생성, 메서드 호출, for한번 허용
		MultiplicationTable play = new MultiplicationTable();
		for (int chk = 0; chk != 1;) {
			try {
				chk = play.inputValue(chk);
				play.outputResult();
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
		}
	}
}
package Test03;

import java.util.Scanner;

class MultiplicationTable {
	int input_first, input_last;

	int inputValue(int chk) throws Exception {
		// 입력
		Scanner in = new Scanner(System.in);
		System.out.print("구구단의 시작단을 입력하세요 ");
		this.input_first = in.nextInt();
		System.out.print("구구단의 마지막단을 입력하세요  ");
		this.input_last = in.nextInt();

		// 예외 발생시키기
		if (input_first > input_last) {
			throw new Exception("시작단은 마지막단보다 작아야합니다.");
		}
		if ((input_first < 2) || (input_last > 9)) {
			throw new Exception("구구단은 2~9단을 입력하세요.");
		}
		// 예외가 일어나지 않아야 밑으로 이동
		chk = 1;
		return chk;

	}

	void outputResult() {
		for (int dan = input_first; dan <= input_last; dan += 3) {
			for (int line = 1; line < 10; line++) {
				System.out.printf(dan > input_last ? " " : "%d x %d = %2d  ",
						dan, line, (dan * line));
				System.out.printf(dan + 1 > input_last ? " "
						: "%d x %d = %2d  ", dan + 1, line, ((dan + 1) * line));
				System.out.printf(dan + 2 > input_last ? "\n"
						: "%d x %d = %2d\n", dan + 2, line, ((dan + 2) * line));
			}
			System.out.println("");
		}
	}
}
public class MainClass02 {
	public static void main(String[] args) {
		MultiplicationTable start = new MultiplicationTable();
		start.inputValue();
		start.outputResult();
//		start.outputResult2();
	}
}
import java.util.Scanner;

public class MultiplicationTable {
	int input1, input2;

	void inputValue() {
		// void inputValue() throws Exception{
		int chk = 0;
		while (chk != 1) {
			try {
				// 입력
				Scanner in = new Scanner(System.in);
				System.out.print("first value : ");
				this.input1 = in.nextInt();
				System.out.print("second value : ");
				this.input2 = in.nextInt();

				// 예외 발생시키기
				if ((input1 > input2)) {
					throw new Exception("\n첫번째 값은 뒷자리보다 작은 수를 입력하시오.\n");
				} else if ((input1 > 9) || (input2 > 9)) {
					throw new Exception("\n9 미만의 수를 입력하시오.\n");
				}

				// 예외가 일어나지 않아야 밑으로 이동
				chk = 1;
			} catch (Exception e) {
				System.err.println(e.getMessage());
				// System.err.println(e);
			}
		}
	}

	void outputResult() {
		for (int dan = input1; dan <= input2; dan += 3) {
			for (int line = 1; line < 10; line++) {
				System.out.printf(dan > input2 ? " " : "%d x %d = %2d  ", dan,
						line, (dan * line));
				System.out.printf(dan + 1 > input2 ? " " : "%d x %d = %2d  ",
						dan + 1, line, ((dan + 1) * line));
				System.out.printf(dan + 2 > input2 ? "\n" : "%d x %d = %2d\n",
						dan + 2, line, ((dan + 2) * line));
			}
			System.out.println("");
		}
	}
}


public class StarTest {

	public static void main(String args[]) {
		int input = 5;
		int st = 0;
		input = (input % 2 == 0) ? input - 1 : input;

		for (int line = 0; line < input; line++) { 
			for (int put = 0; put < (input - st); put++) {
				System.out.print((put >= st) ? "*" : " ");
			}
			st = line < (input / 2) ? st + 1 : st - 1;
			System.out.println();
		}
	}
}

설명




public class Star08 {
	public static void main(String args[]) {

		int in = 5;
		int st = 0;
		for (int line = 0; line < in; line++) {
			for (int put = 0; put < in; put++) {
				System.out.print((put > st) && (put<in-st-1) ? "  " : "* ");
			}
			if (line < in / 2) {
				st++;
			} else {
				st--;
			}
			System.out.println();
		}
	}
}


import java.util.Scanner;
public class Star06 {

	public static void main(String args[]) {

		Scanner scan = new Scanner(System.in);
		System.out.print("입력하세요 >> ");
		int in = scan.nextInt();
		int star = 1;

		for (int line = 1; line <= in; line++) {
			for (int k = 1; k <= in; k++) {
				System.out
						.print(((k >= star + 1) && (k <= in - star)) ? "  "
								: "* ");
			}
			if (line <= in / 2) {
				star++;
			} else {
				star--;
			}
			System.out.println();
		}
	}
}

1. 먼저 JAVA를 설치하겠습니다. 따로 홈페이지에서 받는 것이 아니라 apt-get를 통해서 다운받도록 하겠습니다. 터미널에서 입력하시면 됩니다.

 sudo apt-get install openjdk-7-jdk


다운로드 중인 화면입니다.


2. 설치가 끝나시면 환경변수 설정을 하겠습니다.

export JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk [엔터]

ls -tl $JAVA_HOME [엔터]


3. 만약 위의 단계에서 ls 명령을 실행했는데 디렉터리가 없다고 나오면 아래와 같이 JAVA_HOME 환경변수를 설정한다.

JAVA_HOME=$readlink -f /usr/bin/javac | sed "s:bin/javac::") [엔터]

ls -tl $JAVA_HOME [엔터] 


아래와 같은 화면으로 실행됩니다. 마지막은 제대로 설치되었는지 확인하였습니다.


'System > Linux, unix' 카테고리의 다른 글

[centOS] root 비밀번호 변경  (2) 2014.01.16
[UNIX] 폴더, 파일 권한, 그룹권한 변경하기  (0) 2013.10.07
[Linux] 우분투 FTP 설정하기  (0) 2013.09.29
[UNIX] 시스템 명령어  (0) 2013.09.25
package SocialSecurityNumber_02;

import java.util.Scanner;

public class MainClass01 {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.print("주민등록번호 : ");
		String num = in.nextLine();

		CheckNum01 chk = new CheckNum01(num);
		chk.play();
		
	}
package SocialSecurityNumber_02;

import java.util.Calendar;
import java.util.Scanner;

class CheckNum01 {
	StringBuffer num;
	int select;
	int year, month, day, sex, local, age;

	// 생성자
	CheckNum01(String temp) {
		// StringBuffer을 사용하라고 할까봐 넘겨주었는데 그닥...
		this.num = new StringBuffer(temp);

		char firstNum = num.charAt(7);

		this.year = Integer.parseInt(num.substring(0, 2));
		this.month = Integer.parseInt(num.substring(2, 4));
		this.day = Integer.parseInt(num.substring(4, 6));

		switch (firstNum) {
		case '1':
			this.year += 1900;
			this.sex = 0;
			this.local = 0;
			break;
		case '2':
			this.year += 1900;
			this.sex = 1;
			this.local = 0;
			break;
		case '3':
			this.year += 2000;
			this.sex = 0;
			this.local = 0;
			break;
		case '4':
			this.year += 2000;
			this.sex = 1;
			this.local = 0;
			break;
		case '5':
			this.year += 1900;
			this.sex = 0;
			this.local = 1;
			break;
		case '6':
			this.year += 1900;
			this.sex = 1;
			this.local = 1;
			break;
		case '7':
			this.year += 2000;
			this.sex = 0;
			this.local = 1;
			break;
		case '8':
			this.year += 2000;
			this.sex = 1;
			this.local = 1;
			break;
		case '9':
			this.year += 1800;
			this.sex = 0;
			this.local = 0;
			break;
		case '0':
			this.year += 1800;
			this.sex = 1;
			this.local = 0;
			break;
		}
	}

	// 원하는 것을 출력할 수 있도록 물어보는 메서드
	void play() {
		// while(select != 0)
		outerLoop: while (true) {
			System.out
					.println("MENU > 1: 생년월일 / 2: 나이 / 3: 성별 / 4: 내/외국인 / 0: Quit");
			System.out.print("Select Number-> ");
			Scanner in = new Scanner(System.in);
			select = in.nextInt();

			switch (select) {
			case 1:
				brithday();
				break;
			case 2:
				ageChk();
				break;
			case 3:
				sexChk();
				break;
			case 4:
				localChk();
				break;
			case 0:
				break outerLoop;
			// return;
			}
			System.out.println();
		}
		System.out.println("Quit...");
	}

	void brithday() {
		System.out.println("사용자는 '" + year + "년 " + month + "월 " + day
				+ "일생'입니다.");
	}

	void ageChk() {
		Calendar date = Calendar.getInstance();
		age = (date.get(Calendar.YEAR)) - year + 1;
		System.out.println("사용자의 나이는 '" + age + "'살 입니다.");
	}

	void sexChk() {
		System.out.println("사용자의 성별은 '" + (sex != 1 ? "남자" : "여자") + "'입니다.");
	}
	
	void localChk() {
		System.out.println("사용자는 '" +  (local != 1 ? "내국인" : "외국인") + "'입니다.");
	}
}

제가 자주 사용하는 단축키만 정리해 보았습니다.

Ctrl + 1

퀵 픽스

Ctrl + D

한 줄 삭제

Ctrl + Alt + 방향키(↑, ↓)

줄 복사, 블록 복사(블록상태)

Alt + 방향키(↑, ↓)

블록 이동

Ctrl + Shift + F

코드 포맷팅(문법 템플릿에 맞게 들여쓰기)

Ctrl + F11

전에 실행했던 클래스 실행

F3

선언된 변수, 메소드 정의부로 이동

 

 

Ctrl + L

원하는 라인 이동

Ctrl + / or Ctrl + 7

주석 //

Ctrl + Shift + /

블록 주석 /*  */

Ctrl + Shift + \

블록 주석 해제

Alt + Shift + J

해당 메서드/클래스에 대한 주석생성

 

 

Ctrl + Shift + X

대문자로 변환

Ctrl + Shift + Y

소문자로 변환

Ctrl + O

메소드, 필드 확인

Alt + 방향키(←, →)

열려있는 탭 이동 

Ctrl + k

블록한 문자열의 다음번째 문자열 검색

Ctrl + J

단축키 사용 후 단어입력하면 찾기

Ctrl + Shift + T

클래스 찾기

Ctrl + , or .

다음 annotation 이동(에러, 워닝, 북마크)

Alt + Shift + R

선택된 이름 한꺼번에 바꾸기 

  

F11

디버깅 시작

F8

디버깅 계속

F6

디버깅 한줄씩 실행

F5

디버깅 한줄씩 실행 함수 내부로 들어감

 

 

Ctrl + Shift + L

모든 단축키 보기


public class CheckNum {
	private int year, month, day, age, sex, local;
	private String num;
	Calendar date = Calendar.getInstance();

	// 생성자
	CheckNum(String num) {
		this.num = num;
	}

	/**
	 * 910000-'1'234561 생년월일, 성별, 나이 출력하기 1 : 1900년대 내국인 남자, 2: 1900년대 내국인 여자 3
	 * : 2000년대 내국인 남자, 4: 2000년대 내국인 여자 5 : 1900년대 외국인 남자, 6: 1900년대 외국인 여자 7 :
	 * 2000년대 외국인 남자, 8: 2000년대 외국인 여자 9 : 1800년대 내국인 남자, 0: 1800년대 내국인 여자 생년월일
	 * 값을 받고 Calendar 클래스 사용해서 현재나이 구함.
	 */
	void infoPrint() {
		char gender = num.charAt(7);
		year = Integer.parseInt(num.substring(0, 2));
		month = Integer.parseInt(num.substring(2, 4));
		day = Integer.parseInt(num.substring(4, 6));

		// 7번째 숫자로 성별, 년도, 내/외국인 확인
		switch (gender) {
		case '1':
			year += 1900;
			sex = 0;
			local = 1;
			break;
		case '2':
			year += 1900;
			sex = 1;
			local = 1;
			break;
		case '3':
			year += 2000;
			sex = 0;
			local = 1;
			break;
		case '4':
			year += 2000;
			sex = 1;
			local = 1;
			break;
		case '5':
			year += 1900;
			sex = 0;
			local = 0;
			break;
		case '6':
			year += 1900;
			sex = 1;
			local = 0;
			break;
		case '7':
			year += 2000;
			sex = 0;
			local = 0;
			break;
		case '8':
			year += 2000;
			sex = 1;
			local = 0;
			break;
		case '9':
			year += 1800;
			sex = 0;
			local = 1;
			break;
		case '0':
			year += 1800;
			sex = 1;
			local = 1;
			break;
		}
		age = (date.get(Calendar.YEAR)) - year + 1;

		char sexchk = sex != 1 ? '남' : '여';
		System.out.println("성별 : " + sexchk);
		System.out.println("나이 : " + age);
		System.out.println("생년월일 : " + year + "/" + month + "/" + day);
		System.out.println("내국인 : " + (local == 1 ? "yes" : "no"));
	}
}

위 코드가 전체 코드가 아니라 일부이여서 각자 맞게 사용해야한다.


public class Star05 {
	public static void main(String[] args) {
		int in = 9;
		for (int line = in; in / 2 < line; line--) {
			for (int j = 0; j < line; j++) {
				System.out.print((in - line) <= j ? "*" : " ");
			}
			System.out.println("");
		}
	}
}


public class Star04 {
	public static void main(String[] args) {
		int in = 5;
		for (int line = 0; line < in; line++) {
			for (int j = 0; j < in; j++) {
				System.out.print(line <= j ? "*" : " ");
			}
			System.out.println("");
		}
	}

}


public class Star03 {

	public static void main(String[] args) {
		int in = 5;
		for(int line = 0; line < in; line++) {
			for(int j = in; j > 0; j--) {
				System.out.print(j <= line + 1 ? "*" : " ");
			}
			System.out.println("");
		}
	}

}


public class Star02 {

	public static void main(String[] args) {
		int in = 5;
		for (int line = 0; line < in; line++) {
			for (int j = in; j > line; j--) {
				System.out.print("*");
			}
			System.out.println("");
		}
	}

}


public class Star01 {
	public static void main(String args[]) {
		int in = 5;
		for (int line = 0; line < in; line++) {
			for (int j = 0; j <= line; j++) {
				System.out.print("*");
			}
			System.out.println("");
		}
	}
}


 

JSP 태그

1. 디렉티브(Directive)

2. 스크립트 요소(Scripting elements)

3. 주석

4. 액션(Action)

 

1. 디렉티브(Directive)

 문서를 어떻게 처리할 것인지 나타내는 태그.

 페이지와 관련된 정보를 JSP 콘테이너에 보내는 일종의 메세지.

 

<%@ 디렉티브 속성1= "값1" 속성2="값2" ... %>

 

 디렉티브에는 page 디렉티브, include 디렉티브, taglib 디렉티브가 있다.

 page 디렉티브 : 페이지와 관련된 다양한 속성, 기능을 지정.

속성

값 

기본값 

language

스크립트 언어 이름

"java"

contentType

MIME 타입, 문자셋 

"text/html;

charset=ISO-8859-1" 

info 

문자열 

 

import 

클래스 또는 패키지 이름 

 

session

boolean 값 

"true" 

buffer 

버퍼의 크기 or false 

"8kb" 

autoFlush 

boolean 값 

"true" 

isThreadSafe 

boolean 값 

"true" 

errorPage 

로컬 URL 

 

isErrorPage 

boolean 값 

"false" 

extends 

클래스 이름 

 

 하나의 JSP 페이지에 여러 개의 page 디렉티브를 사용할 수 있지만, import 속성을 제외한 나머지 속성들을 같은 페이지에서 여러번 지정할 수 없다. => 중복 X

 

* contentType 속성

JSP 페이지가 생성하는 문서의 MIME(Multipurpose Internet Mail Extensions) 타입을 나타내는 데 사용.

JSP 페이지에서 사용하는 문자셋을 지정하는 데 사용.

 

* info 속성

페이지를 설명해주는 문자열, 일반적으로 제작자, 버전, 저작권 정보등을 포함시키는 것이 좋다.

 

* import 속성

자바를 스크립트 언어로 사용할 경우 자동적으로 java.lang, javax.servlet, javax.setvlet.http, java,setvlet.jsp 패키지를 import 한다.

 

* autoFlush 속성

버퍼가 다 찰 경우 어떻게 처리할 지를 지정한다. true이면, 출력 버퍼는 자동적으로 비워지고, 버퍼에 있던 내용을 요청한 웹 브라우저에 전송하기 위해서 HTTP 서버에 보내진다.

-> 만약 buffer 속성의 값이 "none"일 경우에는 "false"로 지정할 수 없다.

 

* errorPage 속성

catch하지 않은 에외가 발생할 경우, 보여줄 페이지 설정.

속성 값이 '/'로 시작하면 절대  URL, '/'로 시작하지 않으면 상대 URL을 나타낸다.

 

2. 스크립트 요소(Scripting elements)

선언부(declarations), 스크립트릿(scriptlet), 표현식(expressions)로 구성되어 있다.

 선언부(declarations)

 JSP 페이지에서 사용할 메소드와 변수를 정의. 같은 페이지 다른 스크립트 요소에서 참조 가능.

 

<%! 선언부 부분 %>

 

1) 변수의 선언

선언부에서 정의한 변수는 서블릿으로 변환할 때, 서블릿 클래스의 인스턴스 변수로 변환된다.

 <%!

    private int x = 0;

    private int x = 0;

    private String str = "opid";

    private static int sum = 0;  //인스턴스들이 공유하는 클래스 변수로 선언 가능.

%>

 

2) 메소드의 선언

변수와 메소드를 함께 선언할 수도 있다.

 <%!

    int cul(int x, int y){

        int sum = 0;

        sum = x + y;

        return sum;

    }

%>

 

3) JSP 페이지의 라이프사이클(Life-cycle)

초기화 이벤트나 소멸 이벤트가 발생할 경우 사용되는 메서드.

 <%!

    public void jspInit() {

        // 초기화 이벤트와 관련된 처리.

    }

 

    public void jspDestory() {

        // 소멸 이벤트와 관련된 처리.

    }

%>

 

 표현식 

선언부와는 달리 표현식의 결과를 문자열로 변경되어 출력 스트림에 추가한다. 

<%= expression %>

 스크립트릿

일반적인 목적으로 스크립트 언어를 사용할 수 있도록 해 주는 부분이다.

<% 스크립트릿 부분 %>

 

3. 주석

1) 내용주석    <!-- 주석 내용 -->

브라우저 화면에선 보이지 않지만 소스 보기를 통해서 확인할 수 있다.

내용 주석 안에 JSP 표현식을 포함할 수 있으며, 표현식의 값마다 다르게 생성되기 때문에 동적인 주석 내용을 만들수 있다.

 

2) JSP 주석    <%-- 주석 --%>

페이지가 생산하는 내용과는 상관없으며, 오직 JSP파일에서만 보여진다.

 

3) 스크립트 언어 주석    <% ... /* 주석 */ ... %>

자바의 '/*' 와 '*/', '//'를 사용하여 주석 처리를 할 수 있으며,

 스크립트릿이나 선언부 뿐만 아니라 JSP표현식에서도 주석처리 한다. JSP 콘테이너에 의해 완전히 무시되지 않으며, 변환된 서블릿 코드에 나타난다.

 

'Web > JSP(Java Server Page)' 카테고리의 다른 글

[JSP] 정수,실수,문자열에 콤마찍기 NumberFormat  (0) 2013.07.10
[JSP] 한글변환 메서드  (0) 2013.07.05
[JSP] 기본 객체  (0) 2013.06.28
[JSP] 기초, 개념  (0) 2013.06.27

이클립스를 이용해 자바로 작성한 프로그램을 실행시킬 수 있도록 실행파일(exe)로 변환하는 방법에 대해 포스팅하겠습니다. 준비물로는 작성된 소스파일, 이클립스, JSmooth 이렇게 세 가지가 필요합니다.

JSmooth링크와 아래 그림을 통해 다운 받으시면 됩니다.

 

1. JSmooth 설치하기

 

 

 

 

JSmooth 설치가 끝나셨다면 이클립스를 통해 jar파일을 생성하도록 하겠습니다.

 

 

2. *.jar 파일 생성하기

 

프로젝트에 오른쪽 버튼 클릭 후 Export 를 클릭합니다. 

 

Java - Rnuable JAR file 선택 후 Next로 이동합니다.

 

먼저 Export destination에 .jar파일을 저장 할 위치를 지정해주고,

Launch configuration에는 만들고자 하는 클래스와 프로젝트를 선택하고 만들어주시면 됩니다.

 

 

3. JSmooth를 이용하여 exe파일 만들기

 

위 사진은 JSmooth 첫 실행화면입니다.

 

Skeletion Selection에 콘솔창 프로그램이라면 Consol Wrapper을, 윈도우창(AWT, Swing)이라면 Windowed Wrapper을 선택 후, 윈도우창을 선택했을 경우 아래 체크하시기 바랍니다.

 

위에는 .exe 파일의 경로를 선택하시고 아래는 아이콘으로 선택합니다.

 

먼저 아래에 .jar 파일을 선택하시고, 다음 Main class에 메인클래스를 선택합니다.

 

JVM 버전을 작성합니다.

 

모두 마친 후에 Project - compile 을 선택합니다.

 

JSmoonth파일을 생성할 위치를 선택하시고나면 exe파일이 만들어집니다.

 

위 사진과 같이 바탕화면에 두개의 파일이 만들어졌습니다.

이상으로 이클립스를 이용하여 자바 실행파일 만드는 방법에 대한 포스팅을 마치겠습니다.

+ Recent posts