package db.demo3;

import java.sql.Date;

public class UserVO {

	private String id;
	private String name;
	private String pwd;
	private String phone;
	private String email;
	private int point;
	private Date createDate;
	
	public UserVO(String id, String name, String pwd, String phone, String email, int point, Date createDate) {
		super();
		this.id = id;
		this.name = name;
		this.pwd = pwd;
		this.phone = phone;
		this.email = email;
		this.point = point;
		this.createDate = createDate;
	}

	public UserVO() {}
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public int getPoint() {
		return point;
	}

	public void setPoint(int point) {
		this.point = point;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}
}

 

package db.demo3;

import java.util.ArrayList;

public class UserService {
	
	UserDAO userDao = new UserDAO();
	
	public void removeUser(String id) throws Exception {
		UserVO user = userDao.getUserById(id);
		
		if (user == null) {
			throw new Exception("사용자 정보가 존재하지 않습니다.");
		}
		userDao.deleteUser(id);
	}
	
	
	
	public void modifyUserInfo(UserVO newUser) throws Exception {
		UserVO user = userDao.getUserById(newUser.getId());
		if (user == null) {
			throw new Exception("사용자 정보가 존재하지 않습니다.");
		}
		
		user.setName(newUser.getName());
		user.setPhone(newUser.getPhone());
		user.setEmail(newUser.getEmail());
		
		userDao.updateUser(user);
	}

	public UserVO findUserById(String id) throws Exception {
		UserVO user = userDao.getUserById(id);
		if (user == null) {
			throw new Exception("[" + id + "]에 해당하는 사용자 정보를 찾을 수 없습니다.");
		}
		return user;
	}
	
	public ArrayList<UserVO> searchUsers(String name) throws Exception {
		ArrayList<UserVO> users = userDao.searchUsersByName(name);
		if (users.isEmpty()) {
			throw new Exception("[" + name + "]에 해당하는 사용자 정보를 찾을 수 없습니다.");
		}
		
		// 검색된 정보가 있을 경우에만 정보를 반환함
		return users;
		
	}
	public ArrayList<UserVO> getAllUsers() throws Exception {
		ArrayList<UserVO> users = userDao.getAllUsers();
		
		return users;
	}
	
	public void addNewUser(UserVO user) throws Exception {
		
		
		// 사용자가 입력한 아이디로 사용자 정보를 조회한다.
		UserVO dbUser = userDao.getUserById(user.getId());
		// 이미 등록된 사용자 정보가 존재하는지 체크한다.
		if (dbUser != null) {
			throw new Exception("동일한 아이디를 가진 사용자가 이미 존재합니다.");
		}
		
		// 등록된 사용자 정보가 없으면 신규 사용자로 등록한다.
		userDao.addUser(user);
	}
}

 

package db.demo3;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import db.utils.ConnectionUtils;

public class UserDAO {

	// 사용자 정보 변경하기
	public void updateUser(UserVO user) throws Exception {
		String sql = "update store_users set user_name = ? , user_phone = ?, user_email = ? where user_id = ?";
		Connection con = ConnectionUtils.getConnection();
		PreparedStatement pstmt = con.prepareStatement(sql);
		
		pstmt.setString(1, user.getName());
		pstmt.setString(2, user.getPhone());
		pstmt.setString(3, user.getEmail());
		pstmt.setString(4, user.getId());
		pstmt.executeUpdate();
		
		pstmt.close();
		con.close();
	}
	
	// 새로운 사용자 정보 추가하기
	public void addUser(UserVO user) throws Exception {
		String sql = "insert into store_users (user_id, user_name, user_pwd, user_phone, user_email, user_point) "
				+ "values (?, ?, ?, ?, ?, 0)";
		Connection con = ConnectionUtils.getConnection();
		PreparedStatement pstmt = con.prepareStatement(sql);
	
		pstmt.setString(1, user.getId());
		pstmt.setString(2, user.getName());
		pstmt.setString(3, user.getPwd());
		pstmt.setString(4, user.getPhone());
		pstmt.setString(5, user.getEmail());
		pstmt.executeUpdate();
		
		pstmt.close();
		con.close();
	}
	
	// 지정된 아이디에 해당하는 사용자 정보 삭제하기
	public void deleteUser(String id) throws Exception {
		String sql = "delete from store_users where user_id = ?";
		Connection con = ConnectionUtils.getConnection();
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setString(1, id);
		pstmt.executeUpdate();
		
		pstmt.close();
		con.close();
		
	}
	
	// 지정된 이름에 해당하는 사용자 정보 조회하기
	public ArrayList<UserVO> searchUsersByName(String name) throws Exception {
		ArrayList<UserVO> users = new ArrayList<UserVO>();
		
		String sql = "select * from store_users where user_name = ?";
		Connection con = ConnectionUtils.getConnection();
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setString(1, name);
		ResultSet rs = pstmt.executeQuery();
		
		while (rs.next()) {
			UserVO user = new UserVO();
			user.setId(rs.getString("user_id"));
			user.setName(rs.getString("user_name"));
			user.setPwd(rs.getString("user_pwd"));
			user.setPhone(rs.getString("user_phone"));
			user.setEmail(rs.getString("user_email"));
			user.setPoint(rs.getInt("user_point"));
			user.setCreateDate(rs.getDate("user_create_date"));
			
			users.add(user);
		}
		
		rs.close();
		pstmt.close();
		con.close();		
		return users;
	}
	
	
	// 지정된 아이디에 해당하는 사용자 정보 조회하기 1
	public UserVO getUserById (String id) throws Exception {
		UserVO user = null;
		
		String sql = "select * from store_users where user_id = ?";
		Connection con = ConnectionUtils.getConnection();
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setString(1, id);
		ResultSet rs = pstmt.executeQuery();
		
		while (rs.next()) {
			user = new UserVO();
			//UserVO user = new UserVO();
			user.setId(rs.getString("user_id"));
			user.setName(rs.getString("user_name"));
			user.setPwd(rs.getString("user_pwd"));
			user.setPhone(rs.getString("user_phone"));
			user.setEmail(rs.getString("user_email"));
			user.setPoint(rs.getInt("user_point"));
			user.setCreateDate(rs.getDate("user_create_date"));
		}
		rs.close();
		pstmt.close();
		con.close();
		
		return user;
	}
	
	// 전체 사용자 정보 조회하기
	public ArrayList<UserVO> getAllUsers() throws Exception {
		ArrayList<UserVO> users = new ArrayList<UserVO>();
		
		String sql = "select * from store_users order by user_id asc";
		Connection con = ConnectionUtils.getConnection();
		PreparedStatement pstmt = con.prepareStatement(sql);
		ResultSet rs = pstmt.executeQuery();
		
		while (rs.next()) {
			String id = rs.getString("user_id");
			String name = rs.getString("user_name");
			String pwd = rs.getString("user_pwd");
			String phone = rs.getString("user_phone");
			String email = rs.getString("user_email");
			int point = rs.getInt("user_point");
			Date createDate = rs.getDate("user_create_date");
			
			UserVO user = new UserVO();
			user.setId(id);
			user.setName(name);
			user.setPwd(pwd);
			user.setPhone(phone);
			user.setEmail(email);
			user.setPoint(point);
			user.setCreateDate(createDate);
			
			users.add(user);
		}
		rs.close();
		pstmt.close();
		con.close();
		
		return users;
	}
}

 

package db.demo3;

import java.util.ArrayList;
import java.util.Scanner;

public class UserApp {

	public static void main(String[] args) throws Exception {
		Scanner scanner = new Scanner(System.in);
		
		UserService service = new UserService();
		
		while (true) {
			try {
				System.out.println("1. 가입 2. 전체 조회 3. 이름 검색 4. 아이디 검색 5. 삭제 6. 경로 변경 0. 종료");
				
				System.out.println("메뉴 선택> ");
				int menu = scanner.nextInt();
				
				if (menu == 1) {
					System.out.println("[회원 가입]");
					System.out.println("아이디 입력> ");
					String id = scanner.next();
					System.out.println("이름 입력> ");
					String name = scanner.next();
					System.out.println("비밀번호 입력> ");
					String pwd = scanner.next();
					System.out.println("전화번호 입력> ");
					String phone = scanner.next();
					System.out.println("이메일 입력> ");
					String email = scanner.next();
					
					UserVO user = new UserVO();
					user.setId(id);
					user.setName(name);
					user.setPwd(pwd);
					user.setPhone(phone);
					user.setEmail(email);
					
					service.addNewUser(user);
					
				} else if (menu == 2) {
					System.out.println("[전체 조회]");
					
					ArrayList<UserVO> users = service.getAllUsers();
					if (users.isEmpty()) {
						System.out.println("조회된 사용자 정보가 없습니다.");
					} else {
						for (UserVO user : users) {
							System.out.println("아이디: " + user.getId());
							System.out.println("이름: " + user.getName());
							System.out.println("연락처: " + user.getPhone());
							System.out.println();
						}
					}
					
				} else if (menu == 3) {
					System.out.println("[이름으로 검색하기]");
					
					System.out.println("검색할 이름 입력> ");
					String name = scanner.next();
					
					ArrayList<UserVO> users = service.searchUsers(name);
					for (UserVO user : users) {
							System.out.println("아이디: " + user.getId());
							System.out.println("이름: " + user.getName());
							System.out.println("연락처: " + user.getPhone());
							System.out.println();
					}
				} else if (menu == 4) {
					System.out.println("[아이디로 검색하기]");
					
					System.out.println("검색할 아이디 입력> ");
					String id = scanner.next();
					
					UserVO user = service.findUserById(id);
					System.out.println("아이디: " + user.getId());
					System.out.println("이름: " + user.getName());
					System.out.println("연락처: " + user.getPhone());
					System.out.println("이메일: " + user.getEmail());
					System.out.println("포인트: " + user.getPoint());
					System.out.println("가입일: " + user.getCreateDate());
					System.out.println();
					
				} else if (menu == 5) {
					System.out.println("[사용자 정보 삭제]");
					
					System.out.println("삭제 대상 아이디 입력> ");
					String id = scanner.next();
					
					service.removeUser(id);
					
				} else if (menu == 6) {
					System.out.println("[사용자 정보 업데이트]");
					
					System.out.println("변경 대상 아이디 입력> ");
					String id = scanner.next();
					System.out.println("새 이름 입력> ");
					String name = scanner.next();
					System.out.println("새 연락처 입력> ");
					String phone = scanner.next();
					System.out.println("새 이메일 입력> ");
					String email = scanner.next();
					
					UserVO user = new UserVO();
					user.setId(id);
					user.setName(name);
					user.setPhone(phone);
					user.setEmail(email);
					
					service.modifyUserInfo(user);
					
				} else if (menu == 0) {
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println();
		}
		scanner.close();
	}
}

'자바 > jdbc' 카테고리의 다른 글

utils  (0) 2019.06.10
demo2  (0) 2019.06.10
demo1  (0) 2019.06.10
package db.demo2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;
import java.util.Scanner;

public class BookService {

	Scanner scanner = new Scanner(System.in);
	
	// 모든 책 정보를 조회하는 기능
	public void selectAllBooks() throws Exception {
		/*
		 * 1. SQL 정의
		 * 2. 드라이브 메모리 로딩
		 * 3. Connection 획득
		 * 4. PreparedStatement 획득
		 * (5. ?에 값 설정)
		 * 6. 실행
		 * (7. ResultSet 처리)
		 * 8. 자원 해제 
		 */

		String sql = "select book_no, book_title, book_author, book_publisher, book_price, book_pubdate, book_create_date from books";
		Class.forName("oracle.jdbc.OracleDriver");
		Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "zxcv1234");
		PreparedStatement pstmt = conn.prepareStatement(sql);
		
		ResultSet rs = pstmt.executeQuery();
		
		while (rs.next()) {
			int no = rs.getInt("book_no");
			String title = rs.getString("book_title");
			String author = rs.getString("book_author");
			String publisher = rs.getString("book_publisher");
			int price = rs.getInt("book_price");
			String pubdate = rs.getString("book_pubdate");
			Date createdate = rs.getDate("book_create_date");
			
			System.out.println(no + ", " + author + ", " + publisher + ", " + price + ", " + pubdate + ", " + createdate);
		}
		rs.close();
		pstmt.close();
		conn.close();
	}
	
	// 제목을 전달받아서 그 제목에 해당하는 책 정보를 조회하는 기능
	public void selectBooksByTitle(String keyword) throws Exception {
		String sql = "select book_no, book_title, book_author, book_publisher, book_price, book_pubdate, book_create_date from books where book_title like '%' || ? || '%' ";
		
		Class.forName("oracle.jdbc.OracleDriver");
		Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "zxcv1234");
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, keyword);
		ResultSet rs = pstmt.executeQuery();
		
		while (rs.next()) {
			int no = rs.getInt("book_no");
			String title = rs.getString("book_title");
			String author = rs.getString("book_author");
			String publisher = rs.getString("book_publisher");
			int price = rs.getInt("book_price");
			String pubdate = rs.getString("book_pubdate");
			Date createdate = rs.getDate("book_create_date");
			
			System.out.println(no + ", " + title + ", " + author + ", " + publisher + ", " + price + ", " + pubdate + ", " + createdate);
		}
		rs.close();
		pstmt.close();
		conn.close();
		
		
	}
	
	// 책 정보를 전달받아서 db에 저장하는 기능
	public void insertNewBook(int no, String title, String author, String publisher, int price, String pubdate) throws Exception {
		String sql = "insert into books (book_no, book_title, book_author, book_publisher, book_price, book_pubdate) "
				+ " values (?, ?, ?, ?, ?, ?)";
		Class.forName("oracle.jdbc.OracleDriver");
		Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "zxcv1234");
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setInt(1, no);
		pstmt.setString(2, title);
		pstmt.setString(3, author);
		pstmt.setString(4, publisher);
		pstmt.setInt(5, price);
		pstmt.setString(6, pubdate);
		int rs = pstmt.executeUpdate();
		System.out.println(rs + "개의 행이 저장되었습니다.");
		
		pstmt.close();
		conn.close();
		
	}
	
	// 삭제할 책 번호를 전달받아서 DB에서 책 정보를 삭제하는 기능
	public void deleteBookByNo(int no) throws Exception {
		String sql = "delete from books where book_no = ?";
		Class.forName("oracle.jdbc.OracleDriver");
		Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "zxcv1234");
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setInt(1, no);
		int rs = pstmt.executeUpdate();
		System.out.println(rs + "개의 행이 삭제되었습니다.");
		pstmt.close();
		conn.close();
		
	}
	
	// 책 정보를 전달받아서 변경하는 기능
	public void updateBook(int no, String title, String author, String publisher, int price, String pubdate) throws Exception {
		String sql = "update books set book_title = ? , book_author = ?, book_publisher = ?, book_price = ?, book_pubdate = ? where book_no = ?";
		
		Class.forName("oracle.jdbc.OracleDriver");
		Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "zxcv1234");
		PreparedStatement pstmt = conn.prepareStatement(sql);
		
		pstmt.setString(1, title);
		pstmt.setString(2, author);
		pstmt.setString(3, publisher);
		pstmt.setInt(4, price);
		pstmt.setString(5, pubdate);
		pstmt.setInt(6, no);
		
		int rs = pstmt.executeUpdate();
		System.out.println(rs + "개의 행이 변경되었습니다.");
		
		pstmt.close();
		conn.close();
		
	}
	
}

 

package db.demo2;

import java.util.Scanner;

public class BookApp {

	public static void main(String[] args) throws Exception	{
		
		Scanner scanner = new Scanner(System.in);
		BookService service = new BookService();
		
		while (true) {
			System.out.println("1. 전체 조회 2. 제목 검색 3. 책 등록 4. 책 삭제 5. 책 정보 변경 0. 종료");
			
			System.out.println("메뉴 선택> ");
			int selectNo = scanner.nextInt();
			
			if (selectNo == 1) {
				// 모든 책 정보를 조회해서 출력한다.
				service.selectAllBooks();
				
			} else if (selectNo == 2) {
				// 제목을 입력받아서 제목을 포함하고 있는 책 정보를 조회해서 출력한다.
				System.out.println("조회할 책 제목 입력> ");
				String keyword = scanner.next();
				service.selectBooksByTitle(keyword);
			
			} else if (selectNo == 3) {
				// 번호, 제목, 저자, 출판사, 가격, 출판일을 입력받아서 DB에 저장한다.
				System.out.println("저장할 책 번호 입력>");
				int no = scanner.nextInt();
				System.out.println("저장할 책 제목 입력>");
				String title = scanner.next();
				System.out.println("저장할 책 저자 입력>");
				String author = scanner.next();
				System.out.println("저장할 책 출판사 입력>");
				String publisher= scanner.next();
				System.out.println("저장할 책 가격 입력>");
				int price = scanner.nextInt();
				System.out.println("저장할 책 출판일 입력>");
				String pubdate = scanner.next();

				service.insertNewBook(no, title, author, publisher, price, pubdate);

			} else if (selectNo == 4) {
				// 책 번호를 입력받아서 책 정보를 삭제한다.
				System.out.println("삭제할 책 번호 입력> ");
				int no = scanner.nextInt();
				service.deleteBookByNo(no);
				
			} else if (selectNo == 5) {
				// 수정할 책 번호, 변경할 정보(제목, 저자, 출판사, 가격, 출판일)을 입력받아서
				// 책 번호에 해당하는 책 정보를 변경한다.
				
				System.out.println("변경할 책 번호 입력> ");
				int no = scanner.nextInt();
				System.out.println("변경할 책 제목 입력> ");
				String title = scanner.next();
				System.out.println("변경할 책 저자 입력> ");
				String author = scanner.next();
				System.out.println("변경할 책 출판사 입력> ");
				String publisher = scanner.next();
				System.out.println("변경할 책 가격 입력> ");
				int price = scanner.nextInt();
				System.out.println("변경할 책 출판일 입력> ");
				String pubdate = scanner.next();
				
				service.updateBook(no, title, author, publisher, price, pubdate);
				
			} else if (selectNo == 0) {
				System.out.println("종료");
				break;
			} 
		}
	}
}

'자바 > jdbc' 카테고리의 다른 글

utils  (0) 2019.06.10
demo3  (0) 2019.06.10
demo1  (0) 2019.06.10
package db.demo1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class DeleteDemo {

	public static void main(String[] args) throws Exception {
		String sql = "delete from user_contacts where user_name = ?";
		
		Class.forName("oracle.jdbc.OracleDriver");
		Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "zxcv1234");
		
		PreparedStatement pstmt = connection.prepareStatement(sql);
		pstmt.setString(1, "ㅁ마ㅁㅁ마");
		int rowCount = pstmt.executeUpdate();
		System.out.println(rowCount + "개의 행이 삭제되었습니다.");
		
		pstmt.close();
		connection.close();
	}
}

 

package db.demo1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class InsertDemo1 {

	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		
		Scanner scanner = new Scanner(System.in);
		
		System.out.println("주소록 등록 프로그램");
		
		System.out.println("순번입력> ");
		int no = scanner.nextInt();
		System.out.println("이름입력> ");
		String name = scanner.next();
		System.out.println("연락처입력> ");
		String phone = scanner.next();
		
		// 1. JDBC 드라이버 메모리 로딩
		Class.forName("oracle.jdbc.OracleDriver");
		
		// 2. Database와 연결을 유지하는 Connection 객체 획득하기
		String url1 = "jdbc:oracle:thin:@localhost:1521:xe";
		String user = "hr";
		String password = "zxcv1234";
		Connection connection = DriverManager.getConnection(url1, user, password);
		
		// 3. 실행할 쿼리 정의
		String sql = "insert into user_contacts"
				+ "(user_no, user_name, user_phone, user_create_date)"
				+ "values"
				+ "(?, ?, ?, sysdate)";
		
		// 4. 쿼리를 데이터베이스로 전송하는 PreparedStatement 객체 획득하기
		PreparedStatement pstmt = connection.prepareStatement(sql);
		
		// 5. PreparedStatement의 setXXX(인덱스, 값) 메소드를 사용해서 ?와 치환될 값 설정하기
		pstmt.setInt(1, no);
		pstmt.setString(2, name);
		pstmt.setString(3, phone);
		
		// 6. 쿼리 실행
		int rowCount = pstmt.executeUpdate();
		System.out.println(rowCount + "개의 행이 추가되었습니다.");
		
		// 7. 자원 해제 (필수!, 자원 해제는 역순으로!)
		pstmt.close();
		connection.close();
		
	}
}

 

package db.demo1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class SelectDemo {

	public static void main(String[] args) throws Exception {
		String sql = "select * from user_contacts";
		
		Class.forName("oracle.jdbc.OracleDriver");
		Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "zxcv1234");
		PreparedStatement pstmt = conn.prepareStatement(sql);
		ResultSet rs= pstmt.executeQuery();

		while (rs.next()) {
			int no = rs.getInt("user_no");
			String name = rs.getString("user_name");
			String phone = rs.getString("user_phone");
			
			System.out.println(no + ", " + name + ", " + phone);
			
		}
		rs.close();
		pstmt.close();
		conn.close();
	}
}

 

package db.demo1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;

public class UpdateDemo {

	public static void main(String[] args) throws Exception {
		String sql = "update user_contacts "
				+ "set "
				+ "user_name = ?, "
				+ "user_phone = ? "
				+ "where user_no = ? ";
		
		Scanner scanner = new Scanner(System.in);
		
		System.out.println("수정할 사용자 번호 입력> ");
		int no = scanner.nextInt();
		System.out.println("새 이름 입력> ");
		String name = scanner.next();
		System.out.println("새 연락처 입력> ");
		String phone = scanner.next();
		
		Class.forName("oracle.jdbc.OracleDriver");
		Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "zxcv1234");
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, name);
		pstmt.setString(2, phone);
		pstmt.setInt(3, no); // 3은 열 번호. 5 입력시 부적절한 인덱스라며 에러
		int rowCount = pstmt.executeUpdate();
		System.out.println(rowCount + "개의 행이 변경되었습니다.");
		
		pstmt.close();
		conn.close();
		
		
	}
}

 

'자바 > jdbc' 카테고리의 다른 글

utils  (0) 2019.06.10
demo3  (0) 2019.06.10
demo2  (0) 2019.06.10
package demo.thread;

public class MyRunnable implements Runnable {

	@Override
	public void run() {
		System.out.println("MyRunnable run 실행 시작 ");
		for (int i=0; i<100; i++) {
			System.out.println("MyRunnable 실행 " + i);
		}
		System.out.println("MyRunnable run 실행 종료 ");
	}
}

 

package demo.thread;

public class MyRunnableApp {

	public static void main(String[] args) {
		System.out.println("메인 메소드 시작");

		MyRunnable my = new MyRunnable();
		Thread t = new Thread(my);
		t.start();
		
		for (int i=0; i<100; i++) {
			System.out.println("메인 메소드 실행 " + i);
		}
		
		System.out.println("메인 메소드 종료");
	}
}

 

package demo.thread;

public class MyThread extends Thread {

	@Override
	public void run() {
		System.out.println("MyThread의 run() 메소드 실행 시작");
		for (int i=0; i<100; i++) {
			System.out.println("MyThread 실행 중 " + i);
		}
		System.out.println("MyThread의 run() 메소드 실행 종료");
		
	}
}

 

package demo.thread;

public class ThreadApp {

	public static void main(String[] args) {
		
		System.out.println("메인 메소드 실행 시작");
		
		MyThread my = new MyThread();
		YourThread your = new YourThread();
		
		my.start();
		your.start();
		
		for (int i=0; i<100; i++) {
			System.out.println("메인 스레드 실행 " + i);
		}
		
		System.out.println("메인 메소드 실행 종료");
	}
}

 

package demo.thread;

public class YourThread extends Thread {

	@Override
	public void run() {
		System.out.println("YourThread의 run() 메소드 실행 시작");
		for (int i=0; i<100; i++) {
			System.out.println("YourThread 실행 중 " + i);
		}
		System.out.println("YourThread의 run() 메소드 실행 종료");
		
	}
}

'자바 > network' 카테고리의 다른 글

sync  (0) 2019.06.10
store  (0) 2019.06.10
simpleClient  (0) 2019.06.10
mallClient  (0) 2019.06.10
file  (0) 2019.06.10
package demo.sync;

public class ATM implements Runnable {

	private long balance = 1000000;
	
	@Override
	public void run() {
		for (int i=0; i<25; i++) {
			출금();
		}
	}
	
	public synchronized void 출금() {
		System.out.println("현재 잔액 : " + balance);
		System.out.println("출금 시작");
		balance -= 10000;
		System.out.println("출금 종료");
		System.out.println("출금 후 잔액 : " + balance);
	}
}

 

package demo.sync;


public class ATMApp {

	public static void main(String[] args) {
		ATM atm = new ATM();
		
		Thread t1 = new Thread(atm);
		Thread t2 = new Thread(atm);
		Thread t3 = new Thread(atm);
		Thread t4 = new Thread(atm);
		
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
}

 

package demo.sync;

import java.util.ArrayList;
import java.util.Vector;

public class ListRunnable implements Runnable {

	
	@Override
	public void run() {
		ArrayList<String> names = new ArrayList<String>();
		
		for(int i=0; i<100; i++) {
			names.add("홍길동" + i);
		}
		System.out.println(names.size());
	}
}

 

package demo.sync;

public class ListRunnableApp {

	public static void main(String[] args) {
		

		ListRunnable work = new ListRunnable();
		
		Thread t1 = new Thread(work);
		Thread t2 = new Thread(work);
		Thread t3 = new Thread(work);

		t1.start();
		t2.start();
		t3.start();
	
	}
}

'자바 > network' 카테고리의 다른 글

thread  (0) 2019.06.10
store  (0) 2019.06.10
simpleClient  (0) 2019.06.10
mallClient  (0) 2019.06.10
file  (0) 2019.06.10
package demo.store;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class StoreClient {

	public static void main(String[] args) throws Exception {
		Scanner scanner = new Scanner(System.in);              // 사용자의 입력을 받는다.
		
		Socket socket = new Socket("192.168.10.254", 8000);    // 서버에 연결요청을 보낸다.
		
		PrintWriter out = new PrintWriter(socket.getOutputStream(), true); // 서버로 메시지 보낼 때 사용
		BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

		boolean isLogin = false;
		
		while (true) {
			if (!isLogin) {
				System.out.println("1. 가입 2. 로그인 0. 종료");
			} else {
				System.out.println("3. 목록조회 4. 상세조회 5. 장바구니조회 6. 장바구니 담기 7. 내정보 보기 8. 비밀번호 변경 9. 로그아웃 0. 종료");
			}
			
			System.out.println("메뉴 선택> ");
			int selectNo = scanner.nextInt();
			
			if (selectNo == 0) {
				System.out.println("프로그램 종료");
				break;
			} else if (selectNo == 1) {
				// 아이디, 이름, 비밀번호 입력받기
				System.out.println("아이디> ");
				String id = scanner.next();
				System.out.println("비밀번호> ");
				String password = scanner.next();
				System.out.println("이름> ");
				String name = scanner.next();
				
				
				// 입력받은 아이디, 비밀번호, 이름을 서버로 보내기
				out.println("add_user:" + id + ":" + password + ":" + name);
				
				// 서버가 보낸 응답 받기
				// 응답 메시지 화면에 표시하기
				String message = in.readLine();
				System.out.println("응답메시지: " + message);
				
			} else if (selectNo == 2) {
				System.out.println("아이디> ");
				String id = scanner.next();
				System.out.println("비밀번호> ");
				String password = scanner.next();

				out.println("login_user:" + id + ":" + password);
				
				String message = in.readLine();
				System.out.println("응답메시지: " + message);
				
				String[] s = message.split(":");
				if (s[1].equals("success")) {
					isLogin = true;
				}
				
			} else if (selectNo == 3) {
				out.println("view_products");
				
				String message = in.readLine();
				/* Ver1
				String resSubstract = message.substring(18);
				String[] splitted = resSubstract.split(":");
				
				for (int i=0; i < splitted.length; i++) {
				String[] splitted2 = splitted[i].split(",");
					for (int j=0; j<splitted2.length; j++) {
						System.out.println(splitted2[j]);
					}
				}
				*/
				
				
				/* Ver2
				String[] splitted = message.split(":");
				
				for (int i=1; i < splitted.length; i++) {
					String[] splitted2 = splitted[i].split(",");
					for (int j=0; j<splitted2.length; j++) {
						System.out.println(splitted2[j]);
					}
				}
				*/
				
				// Ver3
				String[] a = message.substring(18).split(":");
				for (int i=0; i < a.length; i++) {
					String b[] = a[i].split(",");
					System.out.println("상품번호: " + b[0]);
					System.out.println("상품명: " + b[1]);
					System.out.println("가격: " + b[2]);
				}
				
				
			} else if (selectNo == 4) {
				System.out.println("제품번호 입력>");
				int productNo = scanner.nextInt();
				out.println("detail_product:" + productNo);
				
				String message = in.readLine();
				System.out.println(message);
				
			} else if (selectNo == 5) {
				out.println("view_cart");
				
				String message = in.readLine();
				System.out.println(message);
				
			} else if (selectNo == 6) {
				System.out.println("제품번호 입력>");
				int productNo = scanner.nextInt();
				System.out.println("수량 입력>");
				int amount = scanner.nextInt();
				out.println("add_cart:" + productNo + ":" + amount);
				
				String message = in.readLine();
				System.out.println("응답메시지: " + message);
				
			} else if (selectNo == 7) {
				out.println("view_user");
				
				String message = in.readLine();
				System.out.println("응답메시지: " + message);
				
			} else if (selectNo == 8) {
				String oldPassword = scanner.next();
				String newPassword = scanner.next();
				out.println("change_pwd:" + oldPassword + ":" + newPassword);
				
				String message = in.readLine();
				System.out.println("응답메시지: " + message);
				
			} else if (selectNo == 9) {
				out.println("logout_user");
				
				String message = in.readLine();
				System.out.println("응답메시지: " + message);
			}
		}
	}
}
package demo.store;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class Server {

	public static void main(String[] args) throws Exception {
		
		ServerSocket server = new ServerSocket(8000);
		ArrayList<User> users = new ArrayList<User>();
		ArrayList<Product> products = new ArrayList<Product>();
		ArrayList<Item> carts = new ArrayList<Item>();
		
		User session = null;
		
		while (true) {
			
			Socket socket = server.accept();
			
			// 스트림 연결
			
			// 클라이언트가 보낸 메세지 읽기
			String text = in.readLine();
			
			String[] values = text.split(":");
			// 메세지 해석 add_user:hong:zxcv1234:홍길동
			//             view_carts
			//             detail_product:100
			if ("add_user".equals(values[0])) {
				// 전달된 값을 User객체 생성해서 담고
				// User객체를 위에서 생성한 ArrayList에 담기
				
				// 클라이언트에 응답보내기
				out.println("res_add_user:success");
				
			} else if ("login_user".equals(values[1])) {
				
			}
		}
	}
}

'자바 > network' 카테고리의 다른 글

thread  (0) 2019.06.10
sync  (0) 2019.06.10
simpleClient  (0) 2019.06.10
mallClient  (0) 2019.06.10
file  (0) 2019.06.10
package demo.simple;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class SimpleClient {

	public static void main(String[] args) throws Exception {
		
		// 서버에 연결 요청
		Socket socket = new Socket("192.168.10.254", 8000);
		
		OutputStream out = socket.getOutputStream();
		InputStream in = socket.getInputStream();
		
		PrintWriter writer = new PrintWriter(out);
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		
		// 서버로 메시지 보내기
		writer.println("");
		writer.flush();
		
		// 서버가 보낸 메시지 읽기
		String message = reader.readLine();
		System.out.println("응답메시지: " + message);
		
		socket.close();
		
	}
}

 

package demo.simple;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleServer {

	public static void main(String[] args) throws Exception {
		
		// 클라이언트의 연결 요청을 처리하는 ServerSocket 생성하기
		ServerSocket server = new ServerSocket(8000);
		System.out.println("서버가 시작되었습니다.");
		
		while (true) {
			// Socket accept()
			// 1. 클라이언트의 연결요청이 있을 때까지 프로그램 실행을 일시정지시킨다.
			// 2. 클라이언트의 연결요청이 접수되면 그 클라이언트와 통신할 때 사용할 Socket객체를 제공한다.
			Socket socket = server.accept();
			
			// Socket으로부터 획득한 스트림을 문자열 전송이 가능하도록 적절한 보조 스트림과 연결시키기
			InputStream in = socket.getInputStream();
			OutputStream out = socket.getOutputStream();
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			PrintWriter writer = new PrintWriter(out);
			
			String name = reader.readLine();
			System.out.println("[" + name + "]이 접속하였습니다");
			
		}
		
	}
}

'자바 > network' 카테고리의 다른 글

sync  (0) 2019.06.10
store  (0) 2019.06.10
mallClient  (0) 2019.06.10
file  (0) 2019.06.10
chat  (0) 2019.06.10
package demo.mall;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class MallClient {

	public static void main(String[] args) throws Exception {
		
		Socket socket = new Socket("192.168.10.254", 8000);
		
		PrintWriter out = new PrintWriter(socket.getOutputStream());
		BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		
		Scanner scanner = new Scanner(System.in);
		
		while (true) {
			System.out.println("1. 전체 조회 2. 상세 조회 3. 등록 0. 종료");
			
			System.out.println("메뉴 선택> ");
			int selectNo = scanner.nextInt();
			if (selectNo == 1) {
				out.println("ALL_REQ");
				out.flush();
				
			} else if (selectNo == 2) {
				System.out.println("상품번호 입력> ");
				int productNo = scanner.nextInt();
				out.println("DETAIL_REQ:" + productNo);
				out.flush();
				
			} else if (selectNo == 3) {
				System.out.println("상품명 입력> ");
				String name = scanner.next();
				System.out.println("제조사 입력> ");
				String maker = scanner.next();
				System.out.println("상품 종류> ");
				String type = scanner.next();
				System.out.println("상품가격 입력> ");
				int price = scanner.nextInt();
				
				out.println("ADD_REQ:" + name + "," + maker + "," + type + "," + price);
				out.flush();
				
			} else if (selectNo == 0) {
				break;
			}
			String message = in.readLine();
			System.out.println("응답 메시지: " + message);
		}
	}
}

'자바 > network' 카테고리의 다른 글

sync  (0) 2019.06.10
store  (0) 2019.06.10
simpleClient  (0) 2019.06.10
file  (0) 2019.06.10
chat  (0) 2019.06.10
package demo.file;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.commons.io.IOUtils;

public class FileServer {

	public static void main(String[] args) throws Exception {
		
		// 클라이언트의 연결 요청을 처리할 ServerSocket 생성
		ServerSocket server = new ServerSocket(8000);
		System.out.println("서버가 시작되었습니다.");
		while (true) {
			// 클라이언트의 연결요청이 접수되면 그 클라이언트와 통신할 소켓을 제공받는다.
			Socket socket = server.accept();
			
			// 소켓으로부터 입력스트림/출력스트림 획득
			InputStream in = socket.getInputStream();
			OutputStream out = socket.getOutputStream();
			
			// 위에서 획득한 스트림을 문자열, 정수, 파일데이터를 송수신할 수 있는
			// 보조스트림(DataInpuStream, DataOutputStream)과 연결
			DataInputStream dis = new DataInputStream(in);
			DataOutputStream dos = new DataOutputStream(out);
			
			// 클라이언트가 보낸 문자열, 정수 읽어오기
			String filename = System.currentTimeMillis() + dis.readUTF();
			long filesize = dis.readLong();
			
			// 클라이언트가 보낸 파일을 저장할 스트림 생성하기
			FileOutputStream fos = new FileOutputStream("c:/temp/" + filename);
			System.out.println("["+filename+"] 저장을 시작");
			
			// 클라이언트가 보낸 파일데이터 읽어서 파일로 저장하기
			int readSize = 0;						// 읽어온 파일 데이터를 크기를 저장할 변수
			int len = 0;
			byte[] buf = new byte[1024];
			while ((len=dis.read(buf)) != -1) {		// 1. 스트림으로부터 데이터 읽기
				fos.write(buf, 0, len);				// 2. 파일에 기록하기
				readSize += len;                    // 3. 읽어들인 파일 데이터 크기를 증가시키기
				if (readSize == filesize) {         // 4. 읽어들인 파일의 크기와 파일 사이즈가 일치하면 반복 탈출
					break;
				}
			}
			fos.close();
			System.out.println("["+filename+"] 저장이 완료");
			
			dos.writeUTF("["+filename+"]의 저장이 완료되었습니다.");
			dos.flush();			
		}
	}
}​

 

package demo.file;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import org.apache.commons.io.IOUtils;

public class FileClient {

	public static void main(String[] args) throws Exception {
		// 소켓을 생성해서 서버에 연결요청하기
		Socket socket = new Socket("192.168.10.254", 8000);
		
		// 소켓으로부터 입력스트림/출력스트림 획득하기
		OutputStream out = socket.getOutputStream();
		InputStream in = socket.getInputStream();
		
		// 소켓으로부터 획득한 스트림을 보조스트림과 연결하기
		DataOutputStream dos = new DataOutputStream(out);
		DataInputStream dis = new DataInputStream(in);
	
		File file = new File("c:/temp/suyoung.jpg");
		String filename = file.getName();                // 파일 이름 획득
		long filesize = file.length();                   // 파일 사이즈 획득
		FileInputStream fis = new FileInputStream(file); // 파일 데이터 획득을 위한 입력 스트림 생성
		
		// 서버로 파일명, 파일사이즈, 파일데이터 보내기
		dos.writeUTF(filename);
		dos.writeLong(filesize);
		IOUtils.copy(fis, dos); // FileInputStream으로 읽어서 DataOutputStream으로 복사
		
		// 서버로부터 메시지 받기
		String message = dis.readUTF();
		System.out.println("응답 메시지 : " + message);
		
		socket.close();
		
	}
}

 

'자바 > network' 카테고리의 다른 글

sync  (0) 2019.06.10
store  (0) 2019.06.10
simpleClient  (0) 2019.06.10
mallClient  (0) 2019.06.10
chat  (0) 2019.06.10
package demo.chat;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class ChatClient extends JFrame {

	private JTextArea messageTextArea = new JTextArea();
	private JTextArea inputTextArea = new JTextArea();
	private JButton sendButton = new JButton("전송");
	
	public ChatClient() {
		
		try {
			Socket socket = new Socket("192.168.10.254", 8000);
			
			PrintWriter out = new PrintWriter(socket.getOutputStream());
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			
			// 수신 전용 작업을 실행하는 스레드 생성
			ChatClientThread cct = new ChatClientThread();
			// 서버가 전송한 메시지를 수신하는 스트림 전달
			cct.setIn(in);
			// 메시지를 표현할 콘트롤 전달
			cct.setMessageTextArea(messageTextArea);
			
			cct.start();
			
			setTitle("심플 채팅");
			setLayout(new BorderLayout());
			
			messageTextArea.setEditable(false);
			
			JPanel bottomPanel = new JPanel(new BorderLayout());
			
			JScrollPane scrollPane = new JScrollPane(inputTextArea);
			inputTextArea.setPreferredSize(new Dimension(0, 50));
			bottomPanel.add(scrollPane, BorderLayout.CENTER);
			bottomPanel.add(sendButton, BorderLayout.EAST);
			
			add(new JScrollPane(messageTextArea), BorderLayout.CENTER);
			add(bottomPanel, BorderLayout.SOUTH);
			
			
			setVisible(true);
			setBounds(200, 200, 500, 700);
			setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			
			sendButton.addActionListener(e->{
				// 입력된 텍스트를 읽어오기
				String text = inputTextArea.getText();
				// 서버로 텍스트 보내기
				out.println(text);
				out.flush();
				
				// 입력창의 텍스트 지우기
				inputTextArea.setText("");
			});
			
			// 전송버튼 비활성화
			sendButton.setEnabled(false);
			
			inputTextArea.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent e) {
					// 입력창에 입력된 텍스트를 읽어온다.
					String text = inputTextArea.getText();
					// 텍스트의 길이가 1 이상이면 전송버튼 활성화
					// 입력된 텍스트가 없으면 전송버튼 비활성화
					if (text.length() > 0) {
						sendButton.setEnabled(true);
					} else {
						sendButton.setEnabled(false);
					}
				}
			});
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "서버와 통신 중 오류가 발생하였습니다.", "통신 오류", JOptionPane.ERROR_MESSAGE);
			System.exit(0);
		}
	}
	
	public static void main(String[] args) {
		new ChatClient();
	}
	
}

 

package demo.chat;

import java.io.BufferedReader;

import javax.swing.JOptionPane;
import javax.swing.JTextArea;

public class ChatClientThread extends Thread {

	private JTextArea messageTextArea;
	private BufferedReader in;
	
	//public ChatClientThread(JTextArea messageTextArea, BufferedReader in) {
	//	this.messageTextArea = messageTextArea;
	//	this.in = in;
	//}
	
	public void run() {
		while (true) {
			try {
				// 서버로부터 메시지 수신
				String text = in.readLine();
				
				// 메시지를 채팅창에 표현
				messageTextArea.append(text + "\n");
				messageTextArea.setCaretPosition(messageTextArea.getText().length());
				
			} catch (Exception e) {
				JOptionPane.showMessageDialog(null, "서버와 연결이 끊어졌습니다", "서버 연결 오류", JOptionPane.ERROR_MESSAGE);
				System.exit(0);
			}
		}
	}

	public void setMessageTextArea(JTextArea messageTextArea) {
		this.messageTextArea = messageTextArea;
	}

	public void setIn(BufferedReader in) {
		this.in = in;
	}
}

 

package demo.chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class ChatServer {

	// 서버에 접속한 모든 클라이언트와 통신을 담당하는 스레드(ChatServerThread)를
	// 저장하는 ArrayList객체 생성하기
	private ArrayList<ChatServerThread> threadList = new ArrayList<ChatServerThread>();
	
	public ChatServer() {
		try {
			ServerSocket server = new ServerSocket(8000);
			System.out.println("채팅 서버가 시작됨...");
			
			while (true) {
				try {
					System.out.println("클라이언트의 요청 대기중...");
					// 연결 요청을 수락하고,
					// 연결 요청을 한 클라이언트와 통신하는 소켓 획득하기
					Socket socket = server.accept();
					System.out.println("클라이언트의 연결 완료...");
					
					// 송수신을 담당하는 스레드 만들기
					ChatServerThread thread = new ChatServerThread();
					threadList.add(thread);
					thread.setSocket(socket);
					thread.setThreadList(threadList);
					thread.start();
					
					//BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
					//PrintWriter out = new PrintWriter(socket.getOutputStream());
					
				} catch (Exception e) {
					
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		new ChatServer();
	}
}

 

package demo.chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;

public class ChatServerThread extends Thread {

	private ArrayList<ChatServerThread> threadList;
	private Socket socket;
	private BufferedReader in;
	private PrintWriter out;
	
	public void sendMessage(String message) throws Exception {
		out.println(message);
		out.flush();
	}
	
	public void broadcastMessage(String message) throws Exception {
		for (ChatServerThread thread : threadList) {
			thread.sendMessage(message);
		}
	}
	public void run() {
		try {
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new PrintWriter(socket.getOutputStream());
			
			while (true) {
			
			// 클라이언트가 보낸 메시지 수신하기
			String message = in.readLine();
			
			// 수신된 메시지를 모든 클라이언트에게 보내기
			broadcastMessage(message);
			
			}
			
		} catch (Exception e) {
		}
	}

	public void setThreadList(ArrayList<ChatServerThread> threadList) {
		this.threadList = threadList;
	}

	public void setSocket(Socket socket) {
		this.socket = socket;
	}	
}

'자바 > network' 카테고리의 다른 글

sync  (0) 2019.06.10
store  (0) 2019.06.10
simpleClient  (0) 2019.06.10
mallClient  (0) 2019.06.10
file  (0) 2019.06.10
public interface Pen {
    void draw();
}​

 

public class PenApp {
    public static void main(String[] args) {
        /*
            익명 객체
             - 객체 생성할 수 없는 인터페이스/추상 클래스를 가지고
               객체 생성 시점에 추상화된 메소드를 즉석에서 구현해서 객체를 생성
             - 별도의 구현 클래스의 정의 없이 객체 생성이 가능하다.
        */
        Pen redPen = new Pen() {

            // 추상화된 메소드 재정의
            public void draw() {
                System.out.println("빨갛게 그리기");
            }
        };
        redPen.draw();

        Pen bluePen = new Pen() {
            public void draw() {
                System.out.println("파랗게 그리기");
            }
        };
        bluePen.draw();
    }
}
​

 

public class PhotoShop {
    // Pen인터페이스를 구현한 객체를 전달받아서 선을 그리는 메소드
    public void drawLine(Pen pen) {
        pen.draw();
        System.out.println("선을 그립니다.");
    }
}
​

 

public class PhotoShopApp {
    public static void main(String[] args) {
        PhotoShop ppoShop = new PhotoShop();

        Pen redPen = new Pen() {
            public void draw() {
                System.out.println("빨갛게");
            }
        };
        ppoShop.drawLine(redPen);

        ppoShop.drawLine(new Pen() {
            public void draw() {
                System.out.println("파랗게");
            }
        });
        
        //람다식
        ppoShop.drawLine(() -> System.out.println("노랗게"));
    }
}
​

 

public interface Mouse{
    void click();
    void dbClick();
    void wheel();
}​

 

public abstract class MouseAdapter implements Mouse {
    public void click() {
    
    }

    public void dbClick() {
    
    }
    
    public void wheel() {
    
    }
}​

 

public class MouseApp {
    public static void main(String[] args) {
        Mouse m1 = new Mouse() {
            // 3개 다 해야. 한 개라도 빠지면
            // 컴파일 오류.
            public void click() {
                System.out.println("공격포인트를 클릭한다.");
            }
            
            public void dbClick() {
            
            }

            public void wheel() {
            
            }
        };

        Mouse m2 = new MouseAdapter() {
            public void click() {
                System.out.println("공격포인트를 클릭한다.");
            }
        };
    }
}
​

 

public class Product {
    private int no;
    private String name;
    private int price;
    
    public Product () {}

    public Product (int no, String name, int price) {
        this.no = no;
        this.name = name;
        this.price = price;
    }
    // Getter/Setter 메소드
    public int getNo() {
        return no;
    }
    public String getName() {
        return name;
    }
    public int getPrice() {
        return price;
    }

    public void setNo(int no) {
        this.no = no;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setPrice(int price) {
        this.price = price;
    }
}​

 

public class Order {
    private Product item;
    private Member customer;

    public Order() {}

    public Order(Product item, Member customer) {
        this.item = item;
        this.customer = customer;
    }

    //Getter/Setter
    public Product getItem() {
        return item;
    }

    public void setItem(Product item) {
        this.item = item;
    }

    public Member getCustomer() {
        return customer;
    }

    public void setCustomer(Member customer) {
        this.customer = customer;
    }
}
​

 

public class Member {
    private int memberNo;
    private String name;
    private int password;
    private int point;

    public int getMemberNo() {
        return memberNo;
    }
    public String getName() {
        return name;
    }
    public int getPassword() {
        return password;
    }
    public int getPoint() {
        return point;
    }

    public void setMemberNo(int memberNo) {
        this.memberNo = memberNo;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setPassword(int password) {
        this.password = password;
    }
    public void setPoint(int point) {
        this.point = point;
    }
}
​

 

public class MemberService {
    private Member[] members = new Member[100];        // 회원정보를 저장하는 배열
    private Product[] products = new Product[5];    // 상품정보를 저장하는 배열
    private Order[] orders = new Order[100];        // 주문정보(상품+고객) 저장하는 배열

    private int position = 0;
    private int orderPosition = 0;

    // 로그인된 사용자정보를 담는 세션
    private Member session;

    public MemberService() {
        products[0] = new Product(100, "아이패드", 800000);
        products[1] = new Product(200, "아이폰xs", 1600000);
        products[2] = new Product(300, "갤럭시S10", 2000000);
        products[3] = new Product(400, "맥북프로", 2600000);
        products[4] = new Product(500, "LG그램", 1800000);
    }

    // 세션에 저장된 사용자정보를 반환하는 기능
    public Member getSession() {
        return session;
    }
    
    // 회원정보를 전달받아서 가입시키는 기능(members에 저장하기)
    public void register(Member member) {
        if (position < members.length) {
            members[position++] = member;
            // position++;
        }
    }

    // 회원번호/비밀번호를 전달받아서 로그인처리를 수행하는 기능
    public void login(int memberNo, int password) {
        // member배열에서 for문을 사용해서 사용자(Member객체)를 하나씩 가져온다
        // memberNo 와 Memeber객체의 번호가 일치하는 사용자(Member객체)가 있으면
        // 그 사용자(Member객체)의 가입시 비밀번호와 전달받은 비밀번호를 비교한다.
        // 비밀번호가 일치하면 그 사용자정보(Member객체)를 session에 담는다.
        /*
        boolean isSuccess = false;
        for (Member member : members) {
            if (member != null && memberNo == member.getMemberNo() && member.getPassword() == password) {
                session = member;
                isSuccess = true;
                break;
            } else if (member != null && memberNo == member.getMemberNo() && member.getPassword() != password) {
                System.out.println("비밀번호가 틀렸습니다.");
                isSuccess = true;
                break;
            } 
        }
        if (!isSuccess) {
            System.out.println("회원정보가 없습니다");
        }
        */

        Member foundMember = null;
        for (Member member : members) {
            if (member != null && member.getMemberNo() == memberNo) {
                foundMember = member;
                break;
            }
        }
        // 메소드의 빠른 종료
        // 올바르지 않는 경우를 먼저 검사해서 그 경우에 해당되면 메소드의 실행이 즉시 중단되게 하는 것

        // 고객정보가 존재하지 않으면 즉시 실행 중단
        if (foundMember == null) {
            System.out.println("고객번호와 일치하는 고객이 존재하지 않습니다.");
            return;
        }
        // 비밀번호가 일치하지 않으면 즉시 실행 중단
        if (foundMember.getPassword() != password) {
            System.out.println("비밀번호가 일치하지 않습니다.");
            return;
        }
        // 올바르지 않은 경우를 전부 통과한 경우
        // 로그인처리 작업을 수행한다.
        session = foundMember;
        System.out.println("로그인이 완료되었습니다.");
        System.out.println("["+foundMember.getName()+"]님 환영합니다.");

        /*
        if (foundMember != null) {
            if (foundMember.getPassword() == password) {
                session = foundMember;
                System.out.println("로그인이 완료되었습니다.");
                System.out.println("["+foundMember.getName()+"]님 환영합니다.");
            } else {
                System.out.println("비밀번호가 일치하지 않습니다.");
            }
        } else {
            System.out.println("고객번호와 일치하는 고객이 존재하지 않습니다.");
        }
        */
    }

    // 세션에 저장된 사용자 정보를 비우는 기능
    public void logout() {
        session = null;
    }

    // 모든 회원정보를 출력하는 기능(로그인된 사용자만 사용가능하다)
    public void printAllMembers() {
        if (session == null) {
            System.out.println("로그인 후 사용가능한 기능입니다.");
            return;
        }

        for (Member member : members) {
            printMember(member);
        }
    }

    // 회원번호를 전달받아서 회원정보를 출력하는 기능(로그인된 사용자만 사용가능하다)
    public void printMemberByNo(int memberNo) {
        if (session == null) {
            System.out.println("로그인 후 사용가능한 기능입니다.");
            return;
        }
        
        Member foundM = null;
        for (Member member : members) {
            if (member != null && memberNo == member.getMemberNo()) {
                foundM = member;
                break;
            }
        }
        if (foundM == null) {
            System.out.println("회원정보가 존재하지 않습니다.");
            return;
        }
        printMember(foundM);
    }

    // 회원정보(Member 객체)를 받아서 출력하는 기능
    public void printMember(Member member) {
        if (member != null) {
            System.out.println("회원번호 : " + member.getMemberNo());
            System.out.println("회원이름 : " + member.getName());
            System.out.println("비밀번호 : " + member.getPassword());
            System.out.println("포 인 트 : " + member.getPoint());
            System.out.println();
        }
    }

    // 모든 상품정보를 출력하는 기능
    public void printAllProducts() {
        if (session == null) {
            System.out.println("로그인 후 사용가능한 기능입니다.");
            return;
        }
        
        for (Product product : products) {
            if (product != null) {
                System.out.println("상품번호 : " + product.getNo());
                System.out.println("상품이름 : " + product.getName());
                System.out.println("상품가격 : " + product.getPrice());
                System.out.println();
            }
        }
    }

    // 주문번호를 전달받아서 주문정보를 생성해서 배열에 담는 기능
    public void order(int productNo) {
        // 1. Order객체를 생성한다.
        // 2. 주문번호에 해당하는 상품정보(Product객체)를 배열에서 찾는다.
        // 3. Order객체에 상품정보(Product객체)와 주문자(로그인한 사람) 정보를 저장한다.
        // 4. orders 배열에 주문정보(Order객체)를 저장한다.
        if (session == null) {
            System.out.println("로그인 후 사용가능한 기능입니다.");
            return;
        }

        Order order = new Order();
        Product foundProduct = null;
        for (Product product : products) {
            if (product != null && productNo == product.getNo()) {
                foundProduct = product;
                break;
            }
        }

        if (foundProduct == null) {
            System.out.println("상품번호와 일치하는 상품이 존재하지 않습니다.");
            return;
        }
        order.setItem(foundProduct);
        order.setCustomer(session);
        
        if (orderPosition < orders.length) {
            orders[orderPosition++] = order;
        }
    }

    // 현재 로그인한 사람(Session의 정보 참조)의 주문내역을 출력한다.
    public void printOrderHistory() {
        if (session == null) {
            System.out.println("로그인 후 사용가능한 기능입니다.");
            return;
        }
        
        Order[] foundOrder = new Order[100];
        int foundOrderPosition = 0;
        for (Order order : orders) {
            if (order != null && order.getCustomer().getMemberNo() == session.getMemberNo()) {
                foundOrder[foundOrderPosition++] = order;
            }
        }
        
        if (foundOrder == null) {
            System.out.println("주문내역이 없습니다.");
            return;
        }
        for (Order order : foundOrder) {
            if (order != null) {
                System.out.println("상품번호 : " + order.getItem().getNo());
                System.out.println("상품이름 : " + order.getItem().getName());
                System.out.println("상품가격 : " + order.getItem().getPrice());
                System.out.println();
            }
        }
    }
}​

 

import java.util.Scanner;

public class MemberApp {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        MemberService service = new MemberService();

        for (;;) {
            int selNo1 = -1;
            int selNo2 = -1;
            if (service.getSession() == null) {
                // 로그인되지 않은 회원에게 보여지는 메뉴 
                System.out.println("1.회원가입 2.로그인 0.종료");
                System.out.print("메뉴선택> ");
                selNo1 = sc.nextInt();
            } else {
                // 로그인된 회원에게 보여지는 메뉴
                System.out.println("1.전체출력 2.한명출력 3.상품정보출력 4.주문하기 5.주문내역 6.로그아웃 0.종료");
                System.out.print("메뉴선택> ");
                selNo2 = sc.nextInt();
            }
            System.out.println();

            if (selNo1 == 1) {
                System.out.println("[회원가입]");
                System.out.print("회원번호 입력> ");
                int memberNo = sc.nextInt();
                System.out.print("회원이름 입력> ");
                String name = sc.next();
                System.out.print("비밀번호 입력> ");
                int password = sc.nextInt();

                Member member = new Member();
                member.setMemberNo(memberNo);
                member.setName(name);
                member.setPassword(password);

                service.register(member);
            } else if (selNo1 == 2) {
                System.out.println("[로그인]");
                System.out.print("회원번호 입력> ");
                int memberNo = sc.nextInt();
                System.out.print("비밀번호 입력> ");
                int password = sc.nextInt();

                service.login(memberNo, password);
            } else if (selNo1 == 0) {
                System.out.println("시스템 종료");
                break;
            } else if (selNo2 == 1) {
                System.out.println("[회원 전체출력]");
                service.printAllMembers();
            } else if (selNo2 == 2) {
                System.out.println("[회원 한명출력]");
                System.out.print("회원번호 입력> ");
                int memberNo = sc.nextInt();

                service.printMemberByNo(memberNo);
            } else if (selNo2 == 6) {
                service.logout();
                System.out.println("로그아웃 되었습니다.");
            } else if (selNo2 == 3) {
                System.out.println("[전체 상품정보 출력]");
                service.printAllProducts();
            } else if (selNo2 == 4) {
                System.out.println("[주문하기]");
                System.out.print("상품번호 입력> ");
                int productNo = sc.nextInt();

                service.order(productNo);
            } else if (selNo2 == 5) {
                System.out.println("[주문내역 보기]");
                service.printOrderHistory();
            } else if (selNo2 == 0) {
                System.out.println("시스템 종료");
                break;
            }
            System.out.println();
        }
    }
}
​

'자바 > oop6' 카테고리의 다른 글

Outter, Iterator, List, Account, MyWindow.java  (0) 2019.06.07
public class Outter {
    // 인스턴스 멤버 내부 클래스 
    // Outter 객체가 생성된 다음에만 사용할 수 있는 내부 클래스
    // Outter 객체의 모든 멤버(필드, 메소드)를 사용할 수 있다.
    public class Inner1 {
    
    }
    // 정적 내부 클래스
    // Outter객체 생성 없이 사용할 수 있는 내부 클래스
    // Outter의 정적 멤버(정적 필드, 정적 메소드)만 사용할 수 있다.
    public static class Inner2 {
    
    }

    public void method() {
        int x = 10;
        x = 20;
        // 로컬 내부 클래스
        // 메소드가 실행되는 동안에만 사용할 수 있는 내부 클래스
        // Outter객체의 모든 멤버를 사용할 수 있다.
        // ...
        class Inner3 {
            public void m1() {
                System.out.println(x);
            }
        }
    }
}
​

 

public interface Iterator {

    boolean empty();
    int next();

}​

 

public class List {

    int[] data = {10, 20, 30, 40, 50};

    public Iterator getIterator() {
        Iterator it = new ListIterator();
        return it;

    }
    class ListIterator implements Iterator {
        int[] clone;
        int position;
    
        public ListIterator() {
            clone = data;
            position = 0;
        }
            
        public int next() {
            int number = 0;
            number = clone[position];
            position++;

            return number;
        }

        public boolean empty () {
            if (position < clone.length) {
                return false;
            } else {
                return true;
            }
        }
    }
}
​

 

public class IteratorApp {
    public static void main(String[] args) {
        List list = new List();
        Iterator iterator = list.getIterator();

        System.out.println(iterator.empty());
        System.out.println(iterator.next());
        System.out.println(iterator.empty());
        System.out.println(iterator.next());
        System.out.println(iterator.empty());
        System.out.println(iterator.next());
        System.out.println(iterator.empty());
        System.out.println(iterator.next());
        System.out.println(iterator.empty());
        System.out.println(iterator.next());

        System.out.println(iterator.empty());    
    }
}
​

 

public class Account {
    private int no;
    private String name;
    private int balance;

    public int getNo() {
        return no;
    }

    public String getName() {
        return name;
    }

    public int getBalance() {
        return balance;
    }

    public static class AccountBuilder {
        private int no;
        private String name;
        private int balance;

        public AccountBuilder no(int no) {
            this.no = no;
            return this;
        }

        public AccountBuilder name(String name) {
            this.name = null;
            this.name = name;
            return this;
        }

        public AccountBuilder balance(int balance) {
            this.balance = 0;
            this.balance = balance;
            return this;
        }

        public Account build() {
            Account account = new Account();
            account.no = no;
            account.name = name;
            account.balance = balance;
            return account;
        }
    }
}
​

 

public class AccountApp {
    public static void main(String[] args) {
        Account.AccountBuilder builder = new Account.AccountBuilder();
        
        builder.no(10).name("홍길동");
        Account account1 = builder.build();
        System.out.println("번호 : " + account1.getNo());
        System.out.println("이름 : " + account1.getName());
        System.out.println("잔고 : " + account1.getBalance());

        builder.no(20).balance(230000);
        Account account2 = builder.build();
        System.out.println("번호 : " + account2.getNo());
        System.out.println("이름 : " + account2.getName());
        System.out.println("잔고 : " + account2.getBalance());

        builder.no(40).name("김유신").balance(430000);
        Account account3 = builder.build();
        System.out.println("번호 : " + account3.getNo());
        System.out.println("이름 : " + account3.getName());
        System.out.println("잔고 : " + account3.getBalance());

        Account account4 = builder.no(50).name("강감찬").balance(5000000).build();
        System.out.println("번호 : " + account4.getNo());
        System.out.println("이름 : " + account4.getName());
        System.out.println("잔고 : " + account4.getBalance());
    }
}
​

 

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MyWindow extends JFrame {

    JTextArea area = new JTextArea();
    JTextField field = new JTextField();
    JButton btn = new JButton("전송");

    public MyWindow() {
        setTitle("연습 프로그램");
        
        JPanel panel = new JPanel(new BorderLayout());
        add(new JScrollPane(area), BorderLayout.CENTER);
        add(panel, BorderLayout.SOUTH);
        panel.add(field, BorderLayout.CENTER);
        panel.add(btn, BorderLayout.EAST);
        
        ActionListener listener = new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                String text = field.getText();
                area.append(text);
                area.append("\n");
                field.setText("");
                field.requestFocus();
            }
        };
        field.addActionListener(listener);
        btn.addActionListener(listener);
    
        setBounds(100, 100, 300, 300);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        field.requestFocus();
    }

    public static void main(String[] args) {
        new MyWindow();
    }
}
​

'자바 > oop6' 카테고리의 다른 글

PhotoShop, Mouse, Member.java  (0) 2019.06.07
public interface Car {
    void start();
    void stop();
    void aircon();
    void radio();
    void navi();
    
}​

 

// Car 인터페이스의 일부 기능을 구현하기 위한 추상 클래스
// 모든 Car구현객체가 동일하게 구현하는 내용을 미리 구현해서
// 구현 클래스의 구현 부담을 줄이는 역할을 수행한다.

public abstract class AbstractCar implements Car {
    public void start() {
        System.out.println("자동차를 출발시킨다.");
    }

    public void stop() {
        System.out.println("자동차를 정지시킨다.");
    }
}​

 

public class Tico extends AbstractCar {
    public void aircon() {
        System.out.println("티코는 찬바람만 나옴");
    }

    public void radio() {
        System.out.println("티코는 라디오가 나옴");
    }

    public void navi() {
        System.out.println("티코는 길찾기 기능을 지원하지 않음");
    }
}
​

 

public interface Highpassable {
    void highpass();
}​

 

public interface HeadupDisplayable {
    void headupDisplay();
}​

 

public interface Camera {
    void record();
    
}​

 

public interface AutoDrivable {
    void  autoDrive();
}​

 

// 인터페이스는 다른 인터페이스를 하나 이상 상속받을 수 있다.
public interface Safeable extends Camera, AutoDrivable {
    void airbag();
}
​

 

public class Genesis extends AbstractCar implements Highpassable, HeadupDisplayable, AutoDrivable {
    public void aircon() {
        System.out.println("제네시스는 설정된 온도로 냉방을 유지함");
    }

    public void radio() {
        System.out.println("제네시스는 자동으로 라디오 주파수 채널을 검색함");

    }

    public void navi() {
        System.out.println("제네시스는 목적지까지 경로를 안내함");
    }

    public void highpass() {
        System.out.println("제네시스는 하이패스를 지원함");
    }

    public void headupDisplay() {
        System.out.println("제네시스는 교통정보를 앞유리창에 표시합니다.");
    }

   public void autoDrive() {
        System.out.println("제네시스는 자율 정보를 표시합니다.");
    }

    public void airbag() {
        System.out.println("제네시스는 에어백을 지원합니다.");
    }
}
​

 

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

        Tico obj1 =  new Tico();
        obj1.start();
        obj1.stop();
        obj1.navi();
        obj1.aircon();
        
        Car obj2 = new Tico();
        obj2.start();
        obj2.stop();
        obj2.navi();
        obj2.aircon();

        Genesis obj3 = new Genesis();
        obj3.start();
        obj3.stop();
        obj3.navi();
        obj3.aircon();
        obj3.autoDrive();
        obj3.highpass();
        obj3.airbag();
        obj3.radio();
        obj3.headupDisplay();

        Car obj4 = new Genesis();
        obj4.start();
        obj4.stop();
        obj4.navi();
        obj4.aircon();

        AutoDrivable car5 = new Genesis();
        car5.autoDrive();
    }
}
​

 

public interface DataReader {
    void read();
}​

 

public class DatabaseDataReader implements DataReader {
    public void read() {
        System.out.println("데이터베이스에서 필요한 데이터를 읽는다.");
    }
}​

 

public class NetworkDataReader implements DataReader {
    public void read() {
        System.out.println("네트워크 통신을 통해서 필요한 데이터를 읽는다.");
    }
}
​

 

public class HRMgr {
    // DataReader 인터페이스를 구현한 객체가 연결될 잭(그릇)을 선언
    private DataReader reader;

    public void setReader(DataReader reader) {
        this.reader=reader;
        }

        public void load() {
            reader.read();
        }
}​

 

public class HRMgrApp {
    public static void main(String[] args) {
        HRMgr mgr = new HRMgr();
        //DataReader인터페이스를 구현한 NetworkDataReader객체 생성
        NetworkDataReader reader1 = new NetworkDataReader();
        //HRMgr의 reader 잭에 위에서 생성한 NetworkDataReader객체 연결
        mgr.setReader(reader1);

        mgr.load();

        DatabaseDataReader reader2 = new DatabaseDataReader();
        mgr.setReader(reader2);
        mgr.load();
    }
}​

 

public class Category {
    private int no;
    private String name;

    // 기본 생성자
    public Category() {}

    // 필드를 초기화하는 생성자
    public Category(int no, String name) {
        this.no = no;
        this.name = name;
    }

    // Getter/Setter 메소드
    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

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

}​

 

public class Product {
    private int no;
    private String name;
    private int price;
    private Category cat;

    // 기본 생성자
    public Product() {}

    // Getter/Setter
    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

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

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public Category getCat() {
        return cat;
    }

    public void setCat(Category cat) {
        this.cat = cat;
    }

    public void printDetail() {
        System.out.println("상품     번호 " + no);
        System.out.println("상품     이름 " + name);
        System.out.println("상품     가격 " + price);
        System.out.println("카테고리 번호 " + cat.getNo());
        System.out.println("카테고리 이름 " + cat.getName());
        System.out.println();
    }
}
​

 

public class MallService {
    private Category[] categories = new Category[10];
    private Product[] products = new Product[100];

    private int catPosition = 0;
    private int proPosition = 0;

    public MallService() {
        categories[catPosition++] = new Category(100, "가구");
        categories[catPosition++] = new Category(200, "가전제품");
        categories[catPosition++] = new Category(300, "주방용품");
        
    }
    
    // 새로운 카테고리 등록 기능
    public void addCategory(Category category) {
    //    for (catPosition; catPosition<categories[].length) {
    //    categories[catPosition] = category;
    //    catPosition++
    //    }
            categories[catPosition] = category;
            catPosition++;
    
    }

    public Category getCategory(int categoryNo) {
        Category category = null;
        
        for (Category cat : categories) {
            if (cat != null && cat.getNo() == categoryNo) {
                category = cat;
            }
        }

        return category;
    }

    public void addProduct(Product product) {
        //for (proPosition; proPosition<products[].length) {
        //products[proPosition] = product;
        //proPosition++
        products[proPosition] = product;
        proPosition++;
        }

    public void printAllCategories() {
        for    (Category c : categories) {
            if (c != null) {
            System.out.print("카테고리 번호 : " + c.getNo());
            System.out.print("카테고리 이름 : " + c.getName());

            }
        }
    }

    public void printAllProducts() {
        for    (Product p : products) {
            if (p != null){
                p.printDetail();
            }
        }
    }
    
    public void printProductsByCategory(int categoryNo) {
        for (Product p : products) {
            if (p != null) {
                Category c = p.getCat();
                if (c.getNo() == categoryNo) {
                p.printDetail();
                }
            }
            // 간소화 버전
            // if (p != null && p.getCat().get() == categotyNo) {
            // p.printDatil();
            // }
        }
    }
}​

 

import java.util.Scanner;

public class MallApp {
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    MallService mall = new MallService();

        for (;;) {
            System.out.println("1. 카테고리 등록 2. 카테고리 출력 3. 상품등록 4. 상품출력 5. 카테고리별 상품출력 0. 종료");
            System.out.print("메뉴 선택> ");
            int selectNo = scanner.nextInt();

            if (selectNo == 1) {
                // 1. 번호와 이름을 입력받는다.
                // 2. Category객체를 생성한다.
                // 3. Category객체의 setter를 사용해서 값을 저장한다.
                // 4. MallService(위에서 생성한 mall리모콘)의 addCategory메소드에게 Category객체를 전달한다.
                System.out.print("번호입력> ");
                int no = scanner.nextInt();
                System.out.print("이름입력> ");
                String name = scanner.next();
            
                Category cat = new Category();

                cat.setNo(no);
                cat.setName(name);
            
                mall.addCategory(cat);

            } else if (selectNo == 2) {
                //System.out.println("카테고리 출력");
                mall.printAllCategories();

            } else if (selectNo == 3) {
                // 1. 카테고리 번호, 상품 번호, 상품 이름, 가격을 입력받는다.
                // 2. Product객체를 생성한다.
                //    Product객체의 setter를 사용해서 상품번호, 이름, 가격을 저장한다.
                //    MallService(위에서 생성한 mall리모콘)의 getCategory메소드에게 1번에서 입력받은 카테고리 번호를
                //      전달해서 번호에 해당하는 Category를 제공받는다.
                // 3. Product객체를 생성한다.
                // 4. Product객체의 setter를 사용해서 상품번호, 이름, 가격, 2번에서 획득한 Category객체를 저장한다.
                // 5. MallService(위에서 생성한 mall리모콘)의 addProduct메소드에게 Product객체를 전달한다.
                System.out.print("카테고리 번호 입력> ");
                int catNo = scanner.nextInt();
                System.out.print("상품 번호 입력> ");
                int proNo = scanner.nextInt();
                System.out.print("상품 이름 입력> ");
                String proName = scanner.next();
                System.out.print("상품 가격 입력> ");
                int proPrice = scanner.nextInt();

                Category c = mall.getCategory(catNo);

                Product product = new Product();
                product.setNo(proNo);
                product.setName(proName);
                product.setPrice(proPrice);
                product.setCat(c);

                mall.addProduct(product);

            } else if (selectNo == 4) {
                mall.printAllProducts();

            } else if (selectNo == 5) {
                System.out.print("카테고리 번호입력> ");
                int catNo = scanner.nextInt();

                mall.printProductsByCategory(catNo);

            } else if (selectNo == 0) {
                System.out.println("프로그램 종료");
                break;
            }
        }
    
    }
}
​

'자바 > oop5' 카테고리의 다른 글

Student, Printer, DatabaseAccess, Member.java  (0) 2019.06.07
public class Score {
    private int kor;
    private int eng;
    private int math;

    public Score() {}

    public Score(int kor, int eng, int math) {
        this.kor = kor;
        this.eng = eng;
        this.math = math;
    }

    public int getKor() {
        return kor;
    }

    public void setKor(int kor) {
        this.kor = kor;
    }

    public int getEng() {
        return eng;
    }

    public void setEng(int eng) {
        this.eng = eng;
    }

    public int getMath() {
        return math;
    }

    public void setMath(int math) {
        this.math = math;
    }
}
​

 

public class Student {
    private int no;
    private String name;
    private Score score;    // Student has a Score (포함 관계)

    public Student() {}

    public int getNo() {
        return no;
    }
    public void setNo(int no) {
        this.no = no;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Score getScore() {
        return score;
    }
    public void setScore(Score score) {
        this.score = score;
    }

}​

 

public class StudentApp {
    public static void main(String[] args) {
    
        // 1. 학생 정보를 저장하는 Student 객체 생성
        // 2. 그 학생의 성적 정보를 담는 Score 객체 생성
        // 3. 1번에서 생성된 Student객체에 성적 정보를 담고 있는 Score객체 전달(Setter 사용)
    
        Student s1 = new Student();
        s1.setNo(10);
        s1.setName("홍길동");

        Score s2 = new Score();
        s2.setKor(100);
        s2.setEng(70);
        s2.setMath(70);

        // Student 객체의 score필드에 Score객체 연결
        s1.setScore(s2);
    
        // 값 출력해보기

        int 번호 = s1.getNo();
        String 이름 = s1.getName();
        /*
        Score 점수 = s1.getScore();
        int 국어 = 점수.getKor();
        int 영어 = 점수.getEng();
        int 수학 = 점수.getMath();
        */

        int 국어 = s1.getScore().getKor();    // 위와 같은 코드임
        int 영어 = s1.getScore().getEng();
        int 수학 = s1.getScore().getMath();

        System.out.println(번호);
        System.out.println(이름);
        System.out.println(국어);
        System.out.println(영어);
        System.out.println(수학);

    }
}​

 

public abstract class Printer{

    public void on() {
        System.out.println("전원 켜기");
    }

    public void off() {
        System.out.println("전원 끄기");
    }

    public void feed() {
        System.out.println("용지 공급하기");
    }
    
    // 추상 메소드 정의
    // 모든 프린터들이 가지고 있는 출력기능(프린터마다 구현 내용이 다를 것으로 예상)을
    // void print()라는 추상 메소드로 추상화함으로써
    // 모든 프린터들이 출력 기능은 void print() {구체적인 구현내용}로 통일되게 정의하게 만듦
    public abstract void print();
}
​

 

public class ColorPrinter extends Printer {
    // Printer 클래스에 정의된 추상 메소드 재정의
    public void print() {
        System.out.println("컬러로 출력합니다.");
    }
    // ColorPrinter의 고유기능
    public void photo() {
        System.out.println("고품질 사진을 출력합니다.");
    
    }
}​

 

public class BlackAndWhitePrinter extends Printer {

    // Printer로부터 상속받은 추상메소드를 구체적인 구현 내용을 가진 메소드로 만든다.
    public void print() {
        System.out.println("흑백으로 출력합니다.");
    }

}
​

 

public class PrinterApp {
    public static void main(String[] args) {
        // 추상 클래스는 new 키워드를 사용해서 객체 생성 할 수 없다.
        // Printer p1 = new Printer();    <--에러

        BlackAndWhitePrinter p2 = new BlackAndWhitePrinter();
        p2.on();
        p2.feed();
        p2.print();
        p2.off();

        Printer p3 = new BlackAndWhitePrinter();
        p3.on();
        p3.feed();
        p3.print();
        p3.off();

        ColorPrinter p4 = new ColorPrinter();
        p4.on();
        p4.feed();
        p4.print();
        p4.off();

        Printer p5 = new ColorPrinter();
        p5.on();
        p5.feed();
        p5.print();
        p5.off();

    }
}​

 

public abstract class DatabaseAccess {
    public void connect() {
        System.out.println("데이터베이스와 연결");
    }
    public void send() {
        System.out.println("데이터베이스에 쿼리문 전송");
    }

    public void receive() {
        System.out.println("데이터베이스로부터 데이터 획득");
    }

    public void disconnect() {
        System.out.println("데이터베이스와 연결 해제");
    }
    
    public abstract void display();

    public void access() {
        connect();
        send();
        receive();
        disconnect();
        display();
    }
}
​

 

public class 성적조회 extends DatabaseAccess {
    public void display() {
        System.out.println("조회된 정보를 성적표에 표시합니다.");
    }
}
​

 

public class 출석부조회 extends DatabaseAccess {
    public void display() {
        System.out.println("조회된 정보를 출석부에 표시합니다.");
    }
}
​

 

public class DatabaseAccessApp {
    public static void main(String[] args) {
        출석부조회 a = new 출석부조회();
        a.access();
    }
}
​

 

public interface MemberService {

    // 추상 메소드
    public abstract void removeAllMemebers();

    //public abstract는 생략가능하다.
    public abstract void printAllMembers();

    public abstract void removeMemberByNo(int no);

    public abstract String getMemberNameByNo(int no);
}
​

 

public class MemberServiceImpl implements MemberService {

    public void removeAllMemebers() {
        System.out.println("엑셀파일에서 모든 회원 정보를 삭제한다.");
    }

    public void printAllMembers() {
        System.out.println("엑셀파일의 모든 회원정보를 출력한다.");
    }

    public void removeMemberByNo(int no) {
        System.out.println("엑셀파일에서 " + no + "번 회원을 삭제한다.");
    }

    public String getMemberNameByNo(int no) {
        String name = null;
        name = "홍길동";
        System.out.println("엑셀파일에서 " + no + "번 회원의 이름을 조회한다.");
        return name;
    }
}​

 

public class MemberApp {
    public static void main(String[] args) {
        //MemberService 인터페이스를 구현한 객체 생성
        MemberServiceImpl service1 = new MemberServiceImpl();
        service1.printAllMembers();

        // 인터페이스를 구현한 객체는 인터페이스 타입의 변수에 담을 수 있다.
        MemberService service2 = new MemberServiceImpl();
    }
}​

'자바 > oop5' 카테고리의 다른 글

Car, HRMgr, Mall.java  (0) 2019.06.07
public class Tire {
    public void go() {
        System.out.println("바퀴가 굴러갑니다.");
    }
}

 

public class SnowTire extends Tire {
    // 재정의
    public void go() {
        System.out.println("눈에서 안전하게 바퀴가 굴러갑니다.");
    }

    public void chain() {
        System.out.println("타이어에 체인을 추가로 장착할 수 있습니다.");
    }
}

 

public class KumhoSnowTire extends SnowTire {
    public void go() {
        System.out.println("금호의 신기술이 적용된 바퀴가 눈을 밀어내며 굴러갑니다.");
    }

    public void push() {
        System.out.println("눈을 바퀴 옆으로 밀어낸다.");
    }
}

 

public class InstanceOfApp {
    public static void main(String[] args) {
    /*
        객체 instanceof 클래스
        Tire t = new Tire();
        t instanceof Tire <-- t가 바라보는 객체가 Tire 종류인가요? true
        t instanceof SnowTire <--t가 바라보는 객체가 SnowTire류 인가요? true
        t instanceof KumhoSnowTire <-- t가 바라보는 객체가 KumhoSnowTire류인가요?
    */

    SnowTire t1 = new SnowTire();
    System.out.println("t1은 Tire류인가요?" + (t1 instanceof Tire));
    System.out.println("t1은 SnowTire류인가요?" + (t1 instanceof SnowTire));
    System.out.println("t1은 KumhoSnowTire류인가요?" + (t1 instanceof KumhoSnowTire));
    }
}

 

public class HankookSnowTire extends SnowTire {
    public void go() {
        System.out.println("한국의 신기술이 적용된 타이어가 눈을 녹이면서 갑니다.");
    }

    public void melt() {
        System.out.println("바퀴로 문을 녹이다.");    
    }
}​

 

public class TireTester {

    public void testTire(SnowTire tire) {
        if (tire instanceof HankookSnowTire) {
            HankookSnowTire t = (HankookSnowTire) tire;
            t.melt();
        } else if (tire instanceof KumhoSnowTire) {
            ((KumhoSnowTire) tire).push();
        }
    }
}

 

public class TireTesterApp {
    public static void main(String[] args) {
        
        TireTester tester = new TireTester();

        Tire t1 = new Tire();
        //tester.testTire(t1);    // 에러. testTire(SnowTire tire)메소드는 SnowTire류 객체만 전달받을 수 있다.

        KumhoSnowTire t2 = new KumhoSnowTire();
        tester.testTire(t2);

        HankookSnowTire t3 = new HankookSnowTire();
        tester.testTire(t3);
    }
}

 

public class TireApp {
    public static void main(String[] args) {
    
    KumhoSnowTire t1 = new KumhoSnowTire();
    SnowTire t2 = new KumhoSnowTire();
    Tire t3 = new KumhoSnowTire();

    t1.go();
    t2.go();
    t3.go();

    }
}

 

public class TireApp2 {
    public static void main(String[] args) {
        
        Tire t1 = new KumhoSnowTire();
        Tire t2 = new HankookSnowTire();
        Tire t3 = new SnowTire();
        Tire t4 = new Tire();

        t1.go();
        t2.go();
        t3.go();
        t4.go();
    }
}

 

public class TireApp3 {
    public static void main(String[] args) {
        // 에러 : 금호스노우타이어 객체를 한국스노우타이어 타입으로 형변환할 수 없다.
        // HankookSnowTire t1 = new KumhoSnowTire();

        // 에러 : 타이어 객체를 스노우타이어 타입으로 형 변환 할 수 없다.
        // 부모 타입 객체를 자식 타입의 참조 변수에 담을 수 없다.
        // SnowTire t1 = new Tire();
    }
}

 

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

    Tire t1 = new KumhoSnowTire();
    t1.go();
    t1.chain();    // 에러
    t1.push();    // 에러

    SnowTire t2 = (SnowTire) t1;
    t2.go();
    t2.chain();
    t2.push();

    }
}

 

public class Pen {
    public void draw() {
        System.out.println("그리다.");
    }
}

 

public class Redpen extends Pen {
    // 재정의
    public void draw() {
        System.out.println("빨갛게 그리다.");
    }

}

 

public class BluePen extends Pen {
    public void draw() {
        System.out.println("파랗게 그리다.");
    }
}

 

public class Painter {
    
    /* 
        매개변수의 다형성
            fillColor 메소드와 drawShape 메소드는 Pen을 상속받는 모든 Pen들을 전달받을 수 있다.
            메소드 내에서 p.draw()를 실행하면 전달받은 XXXPen 객체에 재정의된 draw()가 실행된다.
            * Pen의 종류와 상관없이 draw를 실행하면 실제로 전달받은 객체의 재정의된 draw()가 실행돼서
            펜마다의 고유 기능이 발현된다.
    */

    public void fillColor(Pen p) {
        p.draw();
    }
    
    public void drawShape(Pen p) {
        p.draw();
    }
}

 

public class PainterApp {
    public static void main(String[] args) {
        
        Painter 그림판 = new Painter();

        BluePen pen1 = new BluePen();
        Redpen pen2 = new Redpen();

        그림판.drawShape(pen1);
        그림판.drawShape(pen2);

    }
}

 

public class PhotoShop {
    private Pen pen;

    public PhotoShop() {
    
    }
    
    // Setter 메소드
    public void setPen(Pen pen) {
        this.pen = pen;
    }

    // 도형 그리기 기능
    public void drawShape() {
        pen.draw();
    }
}

 

public class PhotoShopApp {
    public static void main(String[] args) {
    
    PhotoShop ppoShop = new PhotoShop();

    BluePen pen1 = new BluePen();
    ppoShop.setPen(pen1);

    ppoShop.drawShape();

    }
}

'자바 > oop4' 카테고리의 다른 글

Camera, Phone, Car.java  (0) 2019.06.07
public class Camera {
    public void picture() {
        System.out.println("사진을 찍습니다.");
    }

    public void save() {
        System.out.println("사진을 저장합니다.");
    }

    public void delete() {
        System.out.println("사진을 삭제합니다.");
    }
}

 

public class WebCamera extends Camera {
    
    // 메소드 재정의
    public void save() {
        System.out.println("클라우드에 사진을 저장.");
    }

    // 메소드 재정의
    public void delete() {
        System.out.println("클라우드에서 사진을 삭제.");
    }
}

 

public class CameraApp {
    public static void main(String[] args) {
    
        WebCamera c = new WebCamera();

        c.picture();    // 부모로부터 상속받은 기능 사용
        c.save();        // WebCamera에 재정의된 기능 사용
        c.delete();        // WebCamera에 재정의된 기능 사용
    }
}

 

public class Phone {
    String tel;

    public void connect() {
        System.out.println(tel + "에서 전화를 겁니다.");
    }

    public void disconnect() {
        System.out.println(tel + "에서 전화를 끊습니다.");
    }
}

 

public class SmartPhone extends Phone {

    String ipAddress;

    void facetime() {
        System.out.println(tel + "로 화상통화를 시작합니다.");
    }

    void internet() {
        System.out.println(ipAddress + "로 인터넷에 접속합니다.");
    }
}

 

public class PhoneApp {
    public static void main(String[] args) {
    
        Phone p1 = new Phone();
        p1.tel = ("010-2345-5678");
        p1.connect();
        p1.disconnect();
        System.out.println();

        SmartPhone p2 = new SmartPhone();
        p2.tel = ("010-1111-2222");
        p2.connect();
        p2.disconnect();
        p2.ipAddress = ("192.168.10.254");
        p2.internet();
        p2.facetime();
    }
}

 

public class Car {
    // 자식 클래스에 상속되지 않음
    private String name;
    private int speed;
    
    public Car() {
        super();
        System.out.println("Car() 생성자가 실행됨");
    }

    public Car(String name, int speed) {
        super();
        this.name = name;
        this.speed = speed;
        System.out.println("Car(String, int) 생성자 실행됨");
    }

    // Getter/Setter 자식 클래스에 상속됨
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public int getSpeed() {
        return speed;
    }

    public void setSpeed(int speed) {
        this.speed = speed;
    }

    // 자식 클래스에 상속됨 (public 접근 제한이 적용된 필드와 메소드)
    public void Start() {
        System.out.println("출발한다.");
    }
    public void Stop() {
        System.out.println("멈춘다.");
    }

    public void carInfo() {
        System.out.println("### 차량 정보 ###");
        System.out.println("모델명 : " + name);
        System.out.println("속  도 : " + speed);
    }
}

 

public class Sonata extends Car {

    public Sonata() {
        System.out.println("Sonata() 생성자가 실행됨");
    }

    public void currentSpeed() {
        System.out.println("현재속도 : " + getSpeed());

    }

    public void speedUp() {
        int current = getSpeed();
        setSpeed(current + 20);
    }
}

 

public class CarApp {
    public static void main(String[] args) {
    
        /*
        Sonata 객체를 생성할 때 부모 객체인 Car가
        먼저 생성되고 Sonata 객체가 생성된다.
        */

        Sonata car1 = new Sonata();
        car1.speedUp();
        car1.currentSpeed();

        Sonata car2 = new Sonata();
    }
}

 

public class Genesis extends Car {
    private int price;
    
    public Genesis() {
        super();
        System.out.println("Genesis() 생성자가 실행됨");
    }

    public Genesis(String name, int speed, int price) {
        super(name, speed);
        this.price = price;
        System.out.println("Genesis(String, int, int) 생성자 실행됨");
    }

    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }

    public void carInfo() {
        /*
        System.out.println("### 차량 정보 ###");
        System.out.println("모델명 : " + getName());
        System.out.println("속  도 : " + getSpeed());
        */
        super.carInfo(); //    부모 클래스에 정의된 carInfo() 호출
        System.out.println("가  격 : " + price);
    }
}

 

public class CarApp2 {
    public static void main(String[] args) {
        Genesis car1 = new Genesis();
        car1.setName("G90");
        car1.setSpeed(350);
        car1.setPrice(100000000);
        car1.carInfo();

        Genesis car2 = new Genesis("G90L", 400, 150000000);
        car2.carInfo();
    }
}

'자바 > oop4' 카테고리의 다른 글

Tire, PhotoShop.java  (0) 2019.06.07
public class Book {
    private int no;
    private String name;
    private int price;

    public Book() {}

    public Book(int no, String name, int price) {
        this.no = no;
        this.name = name;
        this.price = price;
    }

    // Getter, Setter
    public int getNo() {return no;}
    public String getName() {return name;}
    public int getPrice() {return price;}
    public void setNo(int no) {this.no = no;}
    public void setName(String name) {this.name = name;}
    public void setPrice(int price) {this.price = price;}

}​

 

public class BookService {
    private Book[] database = new Book[10];
    private int position = 0;

    // 새로운 책 정보를 전달받아서 등록하는 기능
    public void addBook(Book book) {
        if (position < database.length) {
            database[position] = book;
            position++;
        }
    }

    // 모든 책 정보를 출력하는 기능
    public void printAllBooks() {
        for (Book book : database) {
            if (book != null) {
                System.out.println("도서번호 : " + book.getNo());
                System.out.println("도서제목 : " + book.getName());
                System.out.println("도서가격 : " + book.getPrice());
            }
        }
    }

    // 최저 가격과 최고 가격을 전달받아서 해당하는 책 정보를 출력하는 기능
    public void printBooksByPrice(int min, int max) {
        for (Book book : database) {
            if (book != null) {
                if (book.getPrice() >= min && book.getPrice() <= max) {
                    System.out.println("도서번호 : " + getNo());
                    System.out.println("도서제목 : " + getName());
                    System.out.println("도서가격 : " + getPrice());
                }
            }
        }
    }

    // 책 번호를 전달받아서 해당 책을 출력하는 기능
    public void printBookByNo(int no) {
        for (Book book : database) {
            if (book != null && book.getNo() == no) {
                System.out.println("도서번호 : " + getNo());
                System.out.println("도서제목 : " + getName());
                System.out.println("도서가격 : " + getPrice());
            }
        }
    }

    // 책 정보를 전달받아서 그 책 번호에 해당하는 책 정보를 변경하는 기능
    public void updateBook(Book book) {
        for (Book b : database) {
            if ( b != null && b.getNo() == book.getNo()) {
                b.setName(book.getName());
                b.setPrice(book.getPrice());
                // 또는
                // String name = book.getName();
                // int price = book.getPrice();
                // b.setNAme(name);
                // b.setPrice(price);
            }
        }
    }

    // 책 번호를 전달받아서 해당 책을 삭제하는 기능
    public void deleteBook(int no) {
        // 삭제할 책의 인덱스를 담을 변수
        int index = -1;        // 절대 일어나지 않을 번지

        for (int i=0; i<position; i++) {
            Book book = database[i];
            if (book.getNo() == no) {
                index = i;
                break;
            }
        }
        
        if (index != -1) {
            if (index < (position -1)) {
                database[index] = database[position - 1];
            }
            database[position-1] = null;
            position--;

        }
    }
}
​

 

import java.util.Scanner;

public class BookApp {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        BookService service = new BookService();

        for (;;) {
            System.out.println("1. 등록 2. 전체 출력 3. 가격별 출력 4. 번호별 출력 5. 수정 6. 삭제 0. 종료");

            /*
                1. 책 번호, 이름, 가격을 입력받아서 Book객체에 담고, Book 객체를 BookService 객체의 addBook메소드에 전달해서 저장
                2. BookService객체의 printAllBooks메소드를 실행해서 전체 책 정보 출력
                3. 최저 가격, 최고 가격을 입력받아서 BookService객체의 printBooksByPrice메소드에 전달해서 책 정보 출력하기
                4. 상품 번호를 입력받아서 BookService객체의 printBookByNo메소드에 전달해서 책 정보 출력하기
                5. 정보를 변경할 책 번호와 새 이름, 새 가격을 입력받아서 Book 객체에 담고, Book 객체를 BookService 객체의 updateBook 메소드에 전달해서 정보 변경하기
                6. 삭제할 책 번호를 입력받아서 BookService객체의 deleteBook 메소드에 전달해서 책 정보 삭제하기
            */
        }

    }
}
 

 

package kr.co.jhta.vo;

public class Professor {
    private String name;

    public Professor() {}
    public String getName() {
        return name;
    }

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

}
​

 

package kr.co.jhta.vo;

public class Student {
    private int no;
    private String name;

    public Student() {
    }
    
    public int getNo() {
        return no;
    }
    
    public String getName() {
    return name;
    }
    
    public void setNo(int no) {
        this.no = no;
    }

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

}
​

 

package kr.co.jhta.app; // 패키지 선언

//import kr.co.jhta.vo.Professor;
//import kr.co.jhta.vo.Student;  // 다른 패키지에 있는 클래스는 import 구문으로 해당 클래스의 전체 경로(패키지 경로 + 클래스)를 명시해야 한다.

import kr.co.jhta.vo.*;

public class StudentApp {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.setNo(20);
        s1.setName("홍길동");

        System.out.println("번호 : " + s1.getNo());
        System.out.println("이름 : " + s1.getName());
    
        Professor p = new Professor();
        p.setName("김교수");
        System.out.println("교수명 : " + p.getName());
    
    }
}
​
// 상품 번호, 상품 이름, 제조사, 상품 가격의 정보를 담는 객체를 위한 설계도
public class Product {

    // 비공개된 필드 정의
    private int no;
    private String name;
    private String maker;
    private int price;

    // 기본 생성자 정의
    public Product() {
    }

    // Getter/Setter 메소드 정의
    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

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

    public String getMaker() {
        return maker;
    }

    public void setMaker(String maker) {
        this.maker = maker;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

}
​

 

public class ProductService {
    private Product[] database = new Product[10]; // 상품 객체 10개를 담는 배열
    private int position = 0; // 상품 객체를 담는 위치

    // 새로운 상품 정보를 배열에 저장하는 기능
    public void addProduct(Product product) {
        if (position < database.length) {
            database[position] = product;
            position++;
        }
    }

    // 모든 상품 정보를 화면에 출력하는 기능
    public void printAllProducts() {
        for (Product p : database) {
            printProduct(p);
        }
    }

    // 전달받은 순서(인덱스)에 해당하는 상품 정보를 제공하는 기능
    public void printProductByIndex(int index) {
    // Product product = null;
        Product p = database[index];
        printProduct(p);
    // return product;
    }

    // 전달받은 상품 번호에 해당하는 상품 정보를 출력하는 기능
    public void printProductByNo(int productNo) {
        for (Product p : database) {
            if (p != null && p.getNo() == productNo) {
                printProduct(p);
            }
        }
    }

    public void printProduct(Product p) {
        if (p != null) {
                System.out.println("상품번호 : " + p.getNo());
                System.out.println("상품이름 : " + p.getName());
                System.out.println("제 조 사 : " + p.getMaker());
                System.out.println("가    격 : " + p.getPrice());
                System.out.println();
        }
    }
}
​

 

import java.util.Scanner;

public class ProductSerivceApp {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // 상품 정보 저장/출력/조회 기능을 제공하는 객체를 생성한다.
        // 아래의 각 선택메뉴에서는 ProductService 객체의 기능을 활용한다.
        ProductService service = new Scanner(System.in);

        for (;;) {
            System.out.println("1. 상품 등록 | 2. 전체 상품 출력 | 3. 순서별 상품 출력 | 4. 상품 번호별 출력 | 0. 종료");
            
            System.out.print("메뉴 선택> ");
            int menuNo = scanner.nextInt();

            if (menuNo == 1) {
                System.out.println("[새 상품 등록]");
                
                System.out.println("번호 입력> ");
                int no = scanner.nextInt();
                System.out.println("이름 입력> ");
                String name = scanner.next();
                System.out.println("제조사 입력> ");
                String maker = scanner.next();
                System.out.println("가격 입력> ");
                int price = scanner.nextInt();

                // 상품 정보를 담는 Product 객체 생성하고 setter를 활용해서 필드에 정보 저장
                Product product = new Product();
                product.setNo(no);
                product.setName(name);
                product.setMaker(maker);
                product.setPrice(price);
                // ProductService 객체가 제공하는 상품 정보를 배열에 저장하는 기능을 실행
                service.addProduct(product);
                // 1. 상품 정보를 입력 받는다.
                // 2. Product 객체를 생성한다.
                // 3. 입력받은 상품 정보를 Product에 담는다.
                // 4. 위에서 생성한 ProductService의 addProduct(Product product) 메소드를 실행해서
                //    상품 정보를 담고 있는 Product가 배열에 저장되게 한다.

            } else if (menuNo == 2) {
                System.out.println("[전체 상품 정보 출력]");
                service.printAllProducts();

            } else if (menuNo == 3) {
                System.out.println("[지정된 인덱스의 상품 정보 출력]");
                System.out.println("인덱스 입력> ");
                int index = scanner.nextInt();
                service.printProductByIndex(index);

            } else if (menuNo == 4) {
                System.out.println("[지정된 상품 번호의 상품 정보 출력]");
                System.out.println("상품 번호 입력> ");
                int no = scanner.nextInt();
                service.printProductByNo(no);

            } else if (menuNo == 0) {
                System.out.println("프로그램 종료");
                break;

            }
            System.out.println();
        }

    }

}
​

 

public class StaticService {
    int x;                // 설계도 로딩 후 -> 객체 생성 후 사용 가능한 필드
    static int y;        // 설계도 로딩 후 사용 가능한 필드
    static final int z = 10;

    public void m1() {
        System.out.println("x의 값: " + x);
        System.out.println("y의 값: " + StaticService.y);
    }

    public static void m2() {
        // static 메소드는 static 필드, static 메소드만 사용(접근) 가능하다.
        // System.out.println("x의 값: " + x);            // 컴파일 오류
        System.out.println("y의 값: " + StaticService.y);
    
    }
}
​

 

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

        // 정적 필드 정적 메소드는 객체 생성없이 즉시 사용가능하다.
        // 클래스명.필드명
        // 클래스명.메소드명(); 과 같은 형태로 사용한다.
        StaticService.y = 10;    // 정적 필드 사용하기
        StaticService.m2();        // 정적 메소드 사용하기

        StaticService.z = 20;
        System.out.println(StaticService.z);
        
    }
}
​

 

import java.util.Date;
import java.text.SimpleDateFormat;

public class StringUtils {
    
    // 홍길동 ---> 홍**
    public static final String NORMAL_DATE_FORMAT = "yyyy-MM-dd";
    public static final String DETAIL_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static String getNormalDate() {
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(NORMAL_DATE_FORMAT);
        return sdf.format(now);
    }

    public static String getDetailDate() {
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(StringUtils.DETAIL_DATE_FORMAT);
        return sdf.format(now);
    }

    public static String hideName(String username) {
        StringBuilder sb = new StringBuilder();
        sb.append(username.substring(0, 1));

        for (int i=0; i<username.length()-1; i++) {
            sb.append("*");
        }
        return sb.toString();
    }
}​

 

public class StringUtilsApp {
    public static void main(String[] args) {
        String name1 = StringUtils.hideName("홍길동");
        System.out.println(name1);

        String name2 = StringUtils.hideName("김구");
        System.out.println(name2);

        String date1 = StringUtils.getNormalDate();
        System.out.println(date1);

        String date2 = StringUtils.getDetailDate();
        System.out.println(date2);
    }
}
​

 

public class Subject {
    int no; // 과목 번호
    String name; // 과목명
    String professor; // 담당 교수

    public Subject() {

    }

    public Subject(int no, String name, String professor) {
    this.no = no;
    this.name = name;
    this.professor = professor;
    }

    // 과목번호(int타입의 값)을 제공하는 메소드
    public int getNo() {
    return no;
    }

    // 새 과목번호(int 타입의 값)을 전달받아서 그 객체의 필드값을 변경하는 메소드
    public void setNo(int no) {
    this.no = no;
    }

    // 과목명(String 타입의 값)을 제공하는 메소드
    public String getName() {
    return name;
    }

    // 새 과목명(String 타입의 값)을 전달받아서 그 객체의 필드값을 변경하는 메소드
    public void setName(String name) {
    this.name = name;
    }

    public String getProfessor() {
    return professor;
    }

    public void setProfessor(String professor) {
    this.professor = professor;
    }

    public void displayInfo() {
        System.out.println("과목번호 : "+ no);
        System.out.println("과목명 : " + name);
        System.out.println("담당교수 : " + professor);

    }
}
​

 

public class SubjectApp {
    public static void main(String[] args) {
    
    Subject s1 = new Subject(10, "전자기학", "홍길동");
    // getter 메소드 사용
    int no1 = s1.getNo();
    String name1 = s1.getName();
    String professor1 = s1.getProfessor();
    System.out.println("과목번호 -> " + no1);
    // setter 메소드 사용
    s1.setProfessor("김유신");
    // s1.displayInfo();
    
    Subject s2 = new Subject(20, "회로이론", "이순신");
    int no2 = s2.getNo();
    String name2 = s2.getName();
    String professor2 = s2.getProfessor();
    System.out.println("과목번호 -> " + no2);

    // s2.displayInfo();    

    }
}​
public class Account {
	int no;			// 계좌번호
	String owner;	// 예금주
	int balance;	// 잔액
	int pwd;		// 비밀번호


	Account(int newNo, String newOwner, int newPwd) {
		no = newNo;
		owner = newOwner;
		pwd = newPwd;
		balance = 0;
	}

	Account(int newNo, String newOwner, int newPwd, int newBalance) {
		no = newNo;
		owner = newOwner;
		pwd = newPwd;
		balance = newBalance;
	}

	// 출력기능
	void displayInfo() {
		System.out.println("계좌번호 : " + no);
		System.out.println("예 금 주 : " + owner);
		System.out.println("비밀번호 : " + pwd);
		System.out.println("잔    액 : " + balance);
		System.out.println();
	}

	// 입금 기능 : 입금액을 전달 받아서 잔액을 증가시키sms 기능
	void deposit(int amount) {
		if (amount > 0) {
			balance += amount;
			System.out.println("입금이 완료되었습니다.");
		} else {
			System.out.println("입금액이 올바르지 않습니다.");
		}
		System.out.println();
	}

	void withdraw(int amount) {
		if (amount < balance) {
			balance -= amount;
			System.out.println("출금이 완료되었습니다.");
		} else {
			System.out.println("출금액이 올바르지 않습니다.");
		}
		System.out.println();
	}

	// 비밀번호 변경 기능 : 이전 비밀번호와 새 비밀번호를 전달받아서 비밀번호를 변경하는 기능
	// 옛날 비밀번호와 새 비밀번호가 일치한다면 비밀번호 변경
	// 일치하지 않으면 화면에 에러메시지 출력

	void changePwd(int oldPwd, int newPwd) {
		if (oldPwd == pwd && newPwd != pwd) {
			pwd = newPwd;
			System.out.println("비밀번호가 정상적으로 변경되었습니다.");
		} else if (oldPwd != pwd) {
			System.out.println("비밀번호가 일치하지 않습니다.");
		} else if (newPwd == pwd) {
			System.out.println("기존의 비밀번호와 동일한 비밀번호를 입력하셨습니다.");
		}
		System.out.println();
	}
}​

 

public class AccountApp {
    public static void main(String[] args) {
    
    // 객체 생성 후 Account(int, String, int) 생성자 메소드 실행
    Account a1 = new Account(10, "홍길동", 1234);

    // 객체 생성 후 Account(int, String, int, int) 생성자 메소드 실행
    Account a2 = new Account(30, "이순신", 5678, 3000000);

        //a1.displayInfo();
        //a1.deposit(100000);
        //a1.displayInfo();
        a1.changePassword(1234, 1111);
        a1.displayInfo();
        //a2.displayInfo();
        //a2.deposit(100000);
        //a2.displayInfo();
        a2.changePassword(1212, 7777);
        a2.displayInfo();

    }
}
​

 

import java.util.Scanner;

public class AccountApp2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        Account[] accounts = new Account[2];

        for (;;) {
            System.out.println("1. 입력 | 2. 조회 | 3. 입금 | 4. 비번변경 | 0. 종료");
            System.out.println();

            System.out.println("메뉴 선택> ");
            int selectNo = scanner.nextInt();

            if (selectNo == 1) {
                for (int i=0; i<2; i++) {
                    // 번호, 소유주, 비번, 잔액을 입력받아서
                    // Account 객체를 생성하고(매개변수 4개 짜리 생성자 활용)
                    // accounts 배열에 담기

                    System.out.println("번호입력> ");
                    int no = scanner.nextInt();
                    System.out.println("소유주입력> ");
                    String owner = scanner.next();
                    System.out.println("비번입력> ");
                    int password = scanner.nextInt();
                    System.out.println("잔액입력> ");
                    int balance = scanner.nextInt();

                    Account a = new Account(no, owner, password, balance);
                    accounts[i] = a;

                }
            } else if (selectNo == 2) {
                for (Account acc : accounts) {
                    acc.displayInfo();
                }

            } else if (selectNo == 3) {
                for (Account acc : accounts) {
                    System.out.println("입금액 입력> ");
                    int a = scanner.nextInt();
                    acc.deposit(a);
                }

            } else if (selectNo == 4) {

            } else if (selectNo == 0) {
                System.out.println("프로그램 종료");
                break;
            }
            System.out.println();
        }
    }
}​

 

public class Book{
    int no;
    String title;
    String writer;
    int price;

    Book() {
    }
    
    Book(int no, String title, String writer, int price) {
        this.no = no;
        this.title = title;
        this.writer = writer;
        this.price = price;
    }

    void displayBookDetail() {
        System.out.println("번호 : " + no);
        System.out.println("제목 : " + title);
        System.out.println("저자 : " + writer);
        System.out.println("가격 : " + price);
    }
}​

 

public class BookApp {
    public static void main(String[] args) {
        Book b1 = new Book();
        b1.displayBookDetail();
        Book b2 = new Book(10, "이것이 자바다", "신용권", 30000);
        b2.displayBookDetail();
        Book b3 = new Book(30, "문제로 풀어보는 알고리즘", "황인욱", 28000);
        b3.displayBookDetail();
    }
}
​

 

public class Car {

    String color;

    // 생성자 정의
    Car() {
        System.out.println("기본 생성자가 실행됨");
        color = "녹턴그레이";
    }

    Car(String customColor) {
        System.out.println("컬러를 전달받는 생성자가 실행됨");
        color = customColor;
    }

    // 필드값을 제공하는 메소드
    String getColor(){
        return color;
    }
    
    // 전달받은 값으로 필드값을 변경하는 메소드
    void setColor(String c) {
    color = c;
    }
}
​

 

public class CarApp {
    public static void main(String[] args) {
        Car car1 = new Car();
        System.out.println(car1.color);            // 필드에 저장된 값 표현
        System.out.println(car1.getColor());    // 조회 메소드를 실행해서 획득한 값 표현
        
        Car car2 = new Car();
        System.out.println(car2.color);
        car2.color = "실버";
        car2.setColor("실버");
        System.out.println(car2.color);

        Car car3 = new Car("화이트");
        System.out.println(car3.color);

        Car car4 = new Car("미드나이트 블랙");
        System.out.println(car4.color);
    }
}
​

 

// 사원 정보를 담는 객체
public class Employee {
    // 사원 번호, 이름, 소속 부서명, 급여, 근무 연수, 전화번호
    // no      name  dept    salary workingYear tel
    
    // 비공개 필드 정의
    private int no;
    private String name;
    private String dept;
    private int salary;
    private int workingYear;
    private String tel;

    // 기본 생성자
    public Employee() {
    }
    
    public Employee(int no, String name, String dept, int salary, int workingYear, String tel) {
        this.no = no;
        this.name = name;
        this.dept = dept;
        this.salary = salary;
        this.workingYear = workingYear;
        this.tel = tel;
    }

    // getter 메소드
    public int getNo() {
        return no;
    }

    public String getName() {
        return name;
    }

    public String getDept() {
        return dept;
    }

    public int getSalary() {
        return salary;
    }

    public int getWorkingYear() {
        return workingYear;
    }

    public String getTel() {
        return tel;
    }

    // setter 메소드
    public void setNo(int no) {
        this.no = no;
    }

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

    public void setDept(String dept) {
        this.dept = dept;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    public void setWorkingYear(int workingYear) {
        this.workingYear = workingYear;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

}
​

 

public class EmployeeApp {
    public static void main(String[] args) {
        // 객체 생성 <-- 기본 생성자 활용
        Employee emp1 = new Employee();
        // setter를 활용해서 필드 초기화
        emp1.setNo(10);
        emp1.setName("홍길동");
        emp1.setDept("영업1팀");
        emp1.setSalary(3000000);
        emp1.setWorkingYear(4);
        emp1.setTel("010-1111-2222");

        // 매개 변수를 전달받는 생성자를 이용해서 필드 초기화
        Employee emp2 = new Employee(20, "김유신", "인사팀", 2500000, 3, "010-3333-4444");

        // Employee 객체 2개 담을 수 있는 배열 객체를 생성해서 employees에 담기
        Employee[] employees = new Employee[2];
        // employees가 참조하는 배열의 0번 째와 1번 째에 위에서 생성한 객체를 담기
        employees[0] = emp1;
        employees[1] = emp2;

        // 배열에 저장된 사원들의 사원 번호와 이름, 급여를 화면에 표시하기
        for (Employee emp : employees) {
            int 사번 = emp.getNo();
            String 이름 = emp.getName();
            int 급여 = emp.getSalary();

            System.out.println("사원 번호 : " + 사번);
            System.out.println("이     름 : " + 이름);
            System.out.println("급     여 : " + 급여);
            
        }
    }
}​

 

public class EmployeeService {
    
    // 새로운 사원 정보를 전달받아서 등록하는 기능
    Employee[] database = new Employee[3];

    public EmployeeService() {
        database[0] = new Employee(10, "김유신", "영업1팀", 250, 2, "010-1234-5678");
        database[1] = new Employee(20, "강감찬", "기술팀", 350, 2, "010-1111-1111");
        database[2] = new Employee(30, "이순신", "인사팀", 300, 2, "010-1234-2222");
    }
    
    // 삭제할 사원 번호를 전달받아서 그 번호에 해당하는 사원 정보를 삭제하는 기능
    
    // 모든 사원 정보를 출력하는 기능
    public void printAllEmployees() {
        for (Employee e : database) {
            int no = e.getNo();
            String name = e.getName();
            String dept = e.getDept();
            int salary = e.getSalary();
            int workingYear = e.getWorkingYear();
            String tel = e.getTel();
        
            System.out.println("사원번호 : " + no);
            System.out.println("사원이름 : " + name);
            System.out.println("소속부서: " + dept);
            System.out.println("실수령액 : " + salary);
            System.out.println("근무연수 : " + workingYear);
            System.out.println("전화번호 : " + tel);
         }
    }
    
    // 조회할 사원 번호를 전달받아서 그 번호에 해당하는 사원 정보를 제공하는 기능
    public Employee getEmployee(int empNo) {
        Employee emp = null;

        for (Employee e : database) {
            if (empNo == e.getNo()) {
                emp = e;
                break;
            }
        }
        
        return emp;
    }
}
​

 

public class EmployeeServiceApp {
    public static void main(String[] args) {
    
        EmployeeService service = new EmployeeService();

        // 모든 사원정보 출력해보기
        service.printAllEmployees();
    
        // 10번 사원 찾기
        Employee emp10 = service.getEmployee(10);
        Employee emp20 = service.getEmployee(20);
        System.out.println(emp10.getNo() + ", " +emp10.getName());
        System.out.println(emp20.getNo() + ", " + emp20.getName());
    }
}
​
public class Book {
    // 필드
    // 제목, 저자, 출판사, 가격, 출판일, 절판 여부

    String title;
    String writer;
    String publisher;
    int price;
    int pubDate;
    boolean sell;
}

 

public class BookUtils {
    // Book 객체 하나를 전달받아서 책 정보를 출력하는 기능
    void printBook(Book book) {
        System.out.println("제    목: " + book.title);
        System.out.println("저    자: " + book.writer);
        System.out.println("출 판 사: " + book.publisher);
        System.out.println("가    격: " + book.price);
        System.out.println("출 판 일: " + book.pubDate);
        System.out.println("판매여부: " + book.sell);
        System.out.println("=======================================");
    }


    // Book 배열을 전달받아서 판매하지 않는 책만 출력하는 기능
    void printBookForSell(Book[] books) {
        for (Book book : books) {
            if (!book.sell == true) {
                printBook(book);
            }
        }
    }


    // Book 배열을 전달받아서 가장 비싼 책(Book)을 제공하는 기능
    Book getExpensiveBook(Book[] books) {
        Book expensiveBook = null;

        int expensivePrice = 0;
        for (Book book : books) {
            if (expensivePrice < book.price) {
            expensivePrice = book.price;
            expensiveBook = book;
            }
        }
        return expensiveBook;
    }
}

 

public class BookPrinter {
    void displayBook(Book book) {
        System.out.println("제    목: " + book.title);
        System.out.println("저    자: " + book.writer);
        System.out.println("출 판 사: " + book.publisher);
        System.out.println("가    격: " + book.price);
        System.out.println("출 판 일: " + book.pubDate );
        System.out.println("판매여부: " + book.sell);

        BookPrinter print = new BookPrinter();

    }
}

 

public class BookApp {
    public static void main(String[] args) {
        // Book 객체 생성 후 책 정보 저장 및 출력하기
        Book b1 = new Book();

        b1.title = "잃어버린 시간을 찾아서";
        b1.writer = "마르셀 프루스트";
        b1.publisher = "비상";
        b1.price = 10000;
        b1.pubDate = 19901023;
        b1.sell = true;

        BookPrinter printer = new BookPrinter();
        printer.displayBook(b1);


    /*  System.out.println(b1.name);
        System.out.println(b1.writer);
        System.out.println(b1.price);
        System.out.println(b1.publishdate);
        System.out.println(b1.sale);
         */
    }
}

 

public class BookApp2 {
    public static void main(String[] args) {
        Book[] books = new Book[3];

        Book book1 = new Book();
        book1.title = "이것이 자바다";
        book1.writer = "신용권";
        book1.publisher = "한빛";
        book1.price = 30000;
        book1.pubDate = 20190228;
        book1.sell = true;

        Book book2 = new Book();    
        book2.title = "자바의 정석";
        book2.writer = "남궁성";
        book2.publisher = "강산북스";
        book2.price = 27000;
        book2.pubDate = 20190101;
        book2.sell = true;

        Book book3 = new Book();
        book3.title = "메롱";
        book3.writer = "메롱의 저자";
        book3.publisher = "메롱의 출판사";
        book3.price = 12345;
        book3.pubDate = 20190301;
        book3.sell = false;


        books[0] = book1;
        books[1] = book2;
        books[2] = book3;

        BookUtils util = new BookUtils();
        System.out.println("----책 정보 출력 기능----");
        util.printBook(book1);
        util.printBook(book2);
        util.printBook(book3);

        System.out.println("----판매하지 않는 책 출력 기능----");
        util.printBookForSell(books);

        System.out.println("----가장 비싼 책 획득하기----");
        Book b = util.getExpensiveBook(books);
        util.printBook(b);
    }
}

 

public class MethodOverloading {
    void m() {
        System.out.println("매개변수 없는 m()이 실행됨");
    }    
    void m(int a) {
        System.out.println("int m()이 실행됨");
    }
    void m(int a, int b) {
        System.out.println("m(int a, int b)이 실행됨");
    }
    void m(String a) {
        System.out.println("m(String a)이 실행됨");
    }
}

 

public class MethodOverloadingApp {
    public static void main(String[] args) {
        MethodOverloading x = new MethodOverloading();

        x.m();
        x.m(20);
        x.m(20, 30);
        x.m("홍길동");
    }
}

+ Recent posts