1) Model/ 데이터 객체 : Value Object(VO), Data Transfer Object(DTO), 데이터베이스의 Table
2) View : 사용자한테 어떤 UI를 보여줄 것인지? 사용자 입력정보, 출력정보
3) Controller : 동작, 제어

 

 

 

Main class

public class FriendInfoMain {
	public static void main(String[] args) {
		FriendInfoView fView = new FriendInfoView();
		fView.menuLoop();
	}
}

 

 

 

Model/ 저장 관리 데이터/ VO/ DTO
- Friend 클래스의 목적
1) 기능을 물려준다
2) Controller에서 자식 객체들을 관리하는 배열변수로서 동작한다. (Friend 객체 자체는 만들지 않는다)

- 추상메서드가 1개이상인 클래스 == 추상 클래스
1) 추상클래스는 객체 제작에 목적이 없다.
2) 자식객체를 담는 변수로서만 동작
3) 일부 기능은 사전 구현해서 상속하지만 일부 기능은 미리 구현하는 것이 어려울 때, 
  선언만 하고 자식클래스에서 구현하는 역할

public abstract class Friend {
	protected String name;
	protected String phoneNum;
	protected String addr;
	
	public Friend(String name, String phone, String addr) {
		this.name = name;
		this.phoneNum = phone;
		this.addr = addr;
	}
	// 전체 정보 출력
	public void showData() {
		System.out.println("이름: " + name);
		System.out.println("전화: " + phoneNum);
		System.out.println("주소: " + addr);
	}
	// 추상 메서드
	// 구현부는 존재하지 않고 선언만 존재하는 메서드
	// 자식이 물려받아서 구현해하는 목적으로 선언
	public abstract void showBasicData();
}
public class HighFriend extends Friend {
	private String work;
	
	public HighFriend(String name, String phone,
				String addr, String job) {
		super(name, phone, addr);
		this.work = job;
	}
	public void showData() {
		super.showData();
		System.out.println("직업 : " + work);
	}
	public void showBasicData() {
		System.out.println("이름 : " + name);
		System.out.println("전화 : " + phoneNum);
	}
}
public class UnivFriend extends Friend {
	private String major;	// 전공학과
	
	public UnivFriend(String name, String phone,
					String addr, String major) {
		super(name, phone, addr);
		this.major = major;
	}
	public void showData() {
		super.showData();
		System.out.println("전공 : " + major);
	}
	public void showBasicData() {
		System.out.println("이름 : " + name);
		System.out.println("전화 : " + phoneNum);
		System.out.println("전공 : " + major);
	}
}

 

 

 

View

화면을 보여주는 역할
입출력 담당 역할

class MENU{
	final static int HIGH_FRIEND = 1;
	final static int UNIV_FRIEND = 2;
	final static int SHOW_ALL = 3;
	final static int SHOW_SIMPLE = 4;
	final static int EXIT_PROGRAM = 5;
}

public class FriendInfoView {
	
	private static Scanner sc = new Scanner(System.in);
	
	FriendInfoController controller;
	
	public FriendInfoView() {
		//controller = new FriendInfoController();
		
		int num = getFriendNum();
		controller = new FriendInfoController(num);
	}
	
	public static Scanner getScanner() {
		return sc;
	}
	
	int getFriendNum() {
		System.out.println("몇 명 친구 저장 ? ");
		int num = sc.nextInt();
		return num;
	}
	
	void viewMenu() {
		System.out.println("*** 메뉴 선택 ***");
		System.out.println("1. 고교 친구 저장");
		System.out.println("2. 대학 친구 저장");
		System.out.println("3. 전체 정보 출력");
		System.out.println("4. 기본 정보 출력");
		System.out.println("5. 프로그램 종료");
	}
	
	int getUserSelect() {
		System.out.println("선택 >> ");
		int choice = sc.nextInt();
		return choice;
	}
	
	boolean runChoice(int choice) {
		switch(choice) {
		case MENU.HIGH_FRIEND:
		case MENU.UNIV_FRIEND:
			controller.addFriend(choice);
			break;
		case MENU.SHOW_ALL:
			controller.showAllData();
			break;
		case MENU.SHOW_SIMPLE:
			controller.showAllSimpleData();
			break;
		case MENU.EXIT_PROGRAM:
			System.out.println("프로그램 종료~");
			return false;
		default:
			System.out.println("잘 못 입력~");
			break;
		}
		
		return true;
	}
	
	void menuLoop() {
		boolean isRun = true;
		while(isRun) {
			viewMenu();
			int choice = getUserSelect();
			isRun = runChoice(choice);
		}
	}
}

 

 

 

Controller

실질적인 동작과 기능을 담당하는 부분

public class FriendInfoController {
	private Friend[] myFriends;	// 친구 객체 저장 배열
	private int numOfFriends;	// 저장된 친구수
	private final static int FRIEND_NUM = 100;
	
	public FriendInfoController() {
		myFriends = new Friend[FRIEND_NUM];
		numOfFriends = 0;
	}
	public FriendInfoController(int num) {
		myFriends = new Friend[num];
		numOfFriends = 0;
	}
	
	// 배열에 친구저장하고, 친구수 증가
	void addFriendInfo(Friend fren) {
		if(numOfFriends < myFriends.length)
			myFriends[numOfFriends++] = fren;
		else
			System.out.println("꽉 찼습니다!!!");
	}
	
	// 고등학교/대학교 친구 입력후 저장
	void addFriend(int choice) {
		String name, phone, addr, job, major;
		
		// 고등학교/대학교 모두 입력받아야 하는 부분
		Scanner sc = FriendInfoView.getScanner();
		System.out.print("이름 : "); name = sc.next();
		System.out.print("전화 : "); phone = sc.next();
		System.out.print("주소 : "); addr = sc.next();
		
		if(choice == MENU.HIGH_FRIEND) {
			System.out.print("직업 : "); job = sc.next();
			addFriendInfo(new HighFriend(name, phone, addr, job));
		}else if(choice == MENU.UNIV_FRIEND) {
			System.out.print("학과 : "); major = sc.next();
			addFriendInfo(new UnivFriend(name, phone, addr, major));
		}
		System.out.println("--- 입력 완료 ---\n");
	}
	
	// 전체 정보 출력
	void showAllData() {
		for(int i=0;i<numOfFriends;i++) {
			myFriends[i].showData();
			System.out.println();
		}
	}
	
	// 기본 정보 출력
	void showAllSimpleData() {
		for(int i=0;i<numOfFriends;i++) {
			myFriends[i].showBasicData();
			System.out.println();
		}
	}
}

'java' 카테고리의 다른 글

Java/ Interface의 개념  (0) 2020.02.10
Java/ MVC패턴과 추상클래스를 이용한 사원 관리 프로그램  (0) 2020.02.10
Java/ equals와 toString의 사용  (0) 2020.02.10
Java/ 상속  (0) 2020.02.10
Java/ String의 개념과 비교  (0) 2020.02.10

모든 Java의 클래스는 Object클래스의 상속을 받는다. Object클래스가 상속하는 Method중에 가장 많이 사용되고 Overriding되는 Method는 equals와 toString이다.



1) toString은 객체의 정보를 나타내는 메서드 
  - 객체가 null일 때는 null을 반환한다.
  - Object에 구현된 내용은 [패키지+클래스이름+@+16진수]로 구성된 hashcode를 반환한다.
  - System.out.println(객체): 이 때 보여지는 정보는 원래 참조값이지만, 내가 원하는 목적의 정보를 보여지게 하는데 종종 사용된다. 
  - String클래스는 문자열 내용이 중요하므로 이미 Overriding되어 객체정보가 아니라 문자열 내용을 반환한다.
     
2) equals와 ==는 동일하다. 객체의 참조값(hashcode)가 같은 지 다른 지를 판단하여 boolean으로 반환한다.(힙의 같은 공간에 할당된 객체인가를 비교) 

- ==은 항상 객체의 참조값을 비교한다. Java의 문자열은 ==을 쓰면 문자열 내용 비교를 할 수 없다.


3) 우리가 내용이 비교하고 싶은 값을 비교해서 판단하고자 하면 equals를 Overriding해서 사용한다. 
 - String클래스는 이미 문자열을 비교하도록 Overriding되어 있다.

 - 다른 클래스도 String클래스처럼 비교하고 싶은 내용으로 Overrding하면 된다. 
  

 

 

ex1)

public class Ball {
	private float rad;
	
	public Ball(float rad) {
		this.rad = rad;
	}
	
	public String showBall() {
		return "이 공의 반지름은 " + rad;
	}
	
	public boolean isEqual(Ball ball) {
		return this.rad == ball.rad;
	}
	
	public static void main(String[] args) {
		Ball ball1 = new Ball(30);
		Ball ball2 = new Ball(30);
		
		System.out.println(ball1.showBall());
		System.out.println(ball2.showBall());
		System.out.println(ball1.isEqual(ball2));
		
		System.out.println(ball1.toString());
		System.out.println(ball2.toString());
		System.out.println(ball1 == ball2);
		System.out.println(ball1.equals(ball2));
	}
}
출력

이 공의 반지름은 30.0
이 공의 반지름은 30.0
true
edu.exam08.tostring01.Ball@15db9742
edu.exam08.tostring01.Ball@6d06d69c
false
false

 

 

ex2)

public class Ball {
	private float rad;
	
	public Ball(float rad) {
		this.rad = rad;
	}
	
	// 객체의 정보를 보여줄 때 Overriding하라고 상속해준 메서드
	public String toString() {
		return "이 공의 반지름은 " + rad;
	}
	
	// 객체내의 정보가 같은 지 여부를 판단 할 때 Overriding하라고 
	// 상속해준 메서드
	public boolean equals(Object obj) {
		return this.rad == ((Ball)obj).rad;
	}
	
	public static void main(String[] args) {
		Ball ball1 = new Ball(30);
		Ball ball2 = new Ball(30);
		
		System.out.println(ball1);	// ball1.toString();
		System.out.println(ball2);	// ball2.toString();
		System.out.println(ball1 == ball2);
		System.out.println(ball1.equals(ball2));
	}
}
출력

이 공의 반지름은 30.0
이 공의 반지름은 30.0
false
true

 

 

ex3)

public class Friend {
	protected String name;
	protected String phoneNum;
	protected String addr;
	
	public Friend(String name, String phone, String addr) {
		this.name = name;
		this.phoneNum = phone;
		this.addr = addr;
	}

	public String toString() {
		return "이름: " + name + "\n" +
			   "전화: " + phoneNum + "\n" +
			   "주소: " + addr + "\n";
	}
	public boolean equals(Object obj) {
		Friend fr = (Friend)obj;
		return this.name.equals(fr.name) &&
			   this.phoneNum.equals(fr.phoneNum) &&
			   this.addr.equals(fr.addr);
	}
	
	public static void main(String[] args) {
		Friend fr0 = new Friend("홍길동", "111", "지리산");
		Friend fr1 = new Friend("홍길동", "111", "지리산");
		Friend fr2 = new Friend("홍길동", "222", "지리산");
		
		System.out.println(fr0);
		System.out.println(fr1);
		System.out.println(fr2);
		System.out.println(fr0.equals(fr1));
		System.out.println(fr0.equals(fr2));
	}
}
출력

이름: 홍길동
전화: 111
주소: 지리산

이름: 홍길동
전화: 111
주소: 지리산

이름: 홍길동
전화: 222
주소: 지리산

true
false

Java inheritance refers to the ability in Java for one class to inherit from another class. In Java this is also called extending a class. One class can extend another class and thereby inherit from that class. When one class inherits from another class in Java, the two classes take on certain roles.

 

Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in java by which one class is allow to inherit the features(fields and methods) of another class.

 

 

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

		System.out.println("tictoceeer");
		Child cd = new Child();
		cd.handsome();
		cd.wealth();
		cd.play();

		System.out.println("외모점수: " + cd.handsomeScore);
		System.out.println("돈: " + cd.money);
		System.out.println("노는날: " + cd.day);
		// child클래스엔 아무 내용이 없지만
		// GrandFather클래스를 extends받았기때문데 GrandFather의 Handsome을 물려받음
		// Father클래스의 wealth도 extends받음

	}
}
//child클래스는 Father클래스를 상속 받는다.
public class Child extends Father{
	float day =365+1.0f/4;//나누기연산 먼저 365+0.25f계산하면서 float로 바뀌
	void play(){
		System.out.println("잼");
	}
}
//Father클래스는 GrandFather클래스를 상속받았다
public class Father extends GrandFather{
	long money=999999999999999L;
	void wealth() {
		System.out.println("부자임");
	}
}
//자바의 모든 클래스는 컴파일되는 순간 오브젝트 클래스의 상속을 받는다.
public class GrandFather {
	int handsomeScore=10;
	void handsome() {
		System.out.println("잘생김");
	}
}

 

ex1) String Instance

//Java.lang.package는 자바의 일반적이고 사용빈도수가 높은 클래스들이 들어있다. import 과정을 생략 가능하다.

public class StringInstance {
	public static void main(String[] args) {
		java.lang.String str="My name is MJ";
		int len=str.length();
		System.out.println("길이: "+ len);
		
		int len1="한글길이".length();
		System.out.println("길이: "+len1);
		
	}
}

 

 

ex2) String간의 비교/ ==과 equals의 차이

//Primitive Type(기본자료형타입)은 ==를 써도 좋다.

public class UnchangeableString {
	public static void main(String[] args) {
		String str0="My String";
		String str1="My String";//별다른 이유없으면 같은 문장은 같은 공간에 저장
		String str2=new String("My String");//새로운 할당 String 저장공간을 만들라// 
		
		
		
		//==의 의미는 같은 객체를 가리키고 있느냐?
		//equals의 의미는 문자열의 내용이 같느냐?
		if (str0==str1)
			System.out.println("같다");
		else
			System.out.println("다르다");
		if(str0==str2)
			System.out.println("같다");
		else
			System.out.println("다르다");
		
		System.out.println("---------");
		
		if (str0.equals(str1))
			System.out.println("같다");
		else
			System.out.println("다르다");
		if(str0.equals(str2))
			System.out.println("같다");
		else
			System.out.println("다르다");
		
		
	}
}
출력

같다
다르다
---------
같다
같다

 

 

ex3) String 같의 결합(concat)/ compareTo를 통한 문자열의 비교

public class StringMethod {
	public static void main(String[] args) {
		String str1="Smart";
		String str2="and";
		String str3="Simple";
		
		//String temp=str1.concat(str2);
		//String str4=temp.concat(str3);
			
			
		String str4=str1.concat(str2).concat(str3);//concat은 스트링을 결합해주는 역할
		System.out.println(str4);
		System.out.println("문자열길이:"+str4.length());
		
		String str5=str1+str2+str3;//concat은 스트링을 결합해주는 역할
		System.out.println(str5);
		System.out.println("문자열길이:"+str5.length());
		
		//str1.equals(str3) true면 같고
		//음수/양수는 다른 문자열, 0이면 같은 문자열
		if (str1.compareTo(str3)==0)
			System.out.println("str1과 str3이 같다.");
		else
			System.out.println("str1과 str3이 다르다.");
		
	}

}
출력

SmartandSimple
문자열길이:14
SmartandSimple
문자열길이:14
str1과 str3이 다르다.

 

 

ex4) 객체참조 비교와 내용비교

public class StringCompare {
	public static void main(String[] args) {
		String str1="Smart";
		String str2="Smart";
		String str3= new String("Smart");
		String str4="Start";
		
		//==는 객체 참조로 비교하기떄문에
		System.out.println("==객체참조로비교");
		if(str1==str2)
			System.out.println("str1과 str2는 같다");
		if(str1==str3)
			System.out.println("str1과 str3는 같다");
		if(str1==str4)
			System.out.println("str1과 str4는 같다");
		
		
		
		//내용비교는 equals로 비교해라 아니면 compareTo
		System.out.println("equals/내용으로 비교");
		if(str1.equals(str2))
			System.out.println("str1과 str2는 같다");
		if(str1.equals(str3))
			System.out.println("str1과 str3는 같다");
		if(str1.equals(str4))
			System.out.println("str1과 str4는 같다");
		
		
		
		
		System.out.println("compareTo/내용으로 비교");
		if(str1.compareTo(str2)==0)
			System.out.println("str1과 str2는 같다");
		if(str1.compareTo(str3)==0)
			System.out.println("str1과 str3는 같다");
		if(str1.compareTo(str4)==0)
			System.out.println("str1과 str4는 같다");
	}
}
출력

==객체참조로비교
str1과 str2는 같다

equals/내용으로 비교
str1과 str2는 같다
str1과 str3는 같다

compareTo/내용으로 비교
str1과 str2는 같다
str1과 str3는 같다

'java' 카테고리의 다른 글

Java/ equals와 toString의 사용  (0) 2020.02.10
Java/ 상속  (0) 2020.02.10
Java/ Static의 개념과 응용  (0) 2020.02.10
Java/ 클래스간의 상호관계  (0) 2020.02.10
Java/Class exc/클래스 응용  (0) 2020.01.28

 

밑변과 높이 정보를 저장할 수 있는 Triangle 클래스 정의
main 클래스에 생성과 동시에 초기화가 가능한 생성자 정의
밑변과 높이 정보를 변경시킬 수 있는 메소드를 정의하여 삼각형의 넓이를 계산해서 반환하는 메소드 객체를 구현

 

 

public class TriangleMain {
	public static void main(String[] args) {
		//생성과 동시에 초기화가 가능한 생성자도 정의
		Triangle ta0 = new Triangle(3,5);
		Triangle ta1 = new Triangle(4,2);
		Triangle ta2 = new Triangle(6,10);//
		
		ta0.res();
		ta1.res();
		ta2.res();
		
	}
}
public class Triangle {
	private int base;
	private int height;


	public Triangle(int base, int height) {
		this.base = base;
		this.height = height;//정보를 변경시킬수있는 메소드정의
	}

	void res() {
		System.out.printf("삼각형의 넓이는 %d이다.\n", base * height / 2);//넓이를 계산해서 반환
	}

}

- static은 객체를 만들지 않아도 클래스를 통해 바로 호출이 가능하다.
- static으로 만드는 메서드는 프로그램이 종료될때까지 계속 존재한다.


- static메서드는 일반적으로 사용되는 utility성 기능과 범용적인 기능들을 구현할 때에 사용된다.

 

 

 

ex1) static 메서드와 일반 메서드 비교

public class CalcMain {
	public static void main(String[] args) {
		Calc calc = new Calc();//일반메소드는 이게 필요-메모리에 올라가지않기 때문에 자주쓰는 기능이 아닌 1회성 use등에 사용(메모리절약)
		System.out.println(calc.add(10, 20));
		System.out.println(calc.sub(10, 20));
		System.out.println(calc.mul(10, 20));
		System.out.println(calc.div(10, 20));
		System.out.println("---------------");
		
		
		
		//static메소드 -메모리에 올라가지만 자주쓰는 기능은 만들어 주는게 편의
		System.out.println(CalcStatic.add(10, 20));
		System.out.println(CalcStatic.sub(10, 20));
		System.out.println(CalcStatic.mul(10, 20));
		System.out.println(CalcStatic.div(10, 20));
	}
}
/*
 * static 메서드는 객체가 생성되어 있지않아도
 * 해당코드가 프로젝트에 포함되어 있으면 메모리에 로딩되게 된다.
 * -> 객체를 생성하지 않아도 사용가능하다.
 */

public class CalcStatic {
	public static float add(float a, float b) {
		return a+b;
	}
	public static float sub(float a, float b) {
		return a-b;
	}
	public static float mul(float a, float b) {
		return a*b;
	}
	public static float div(float a, float b) {
		return a/b;
	}
}
//일반 메서드는 객체생성시 메모리에 로딩된다.
 
public class Calc {
	public float add(float a, float b) {
		return a+b;
	}
	public float sub(float a, float b) {
		return a-b;
	}
	public float mul(float a, float b) {
		return a*b;
	}
	public float div(float a, float b) {
		return a/b;
	}

}

 

 

 

 

ex2) static 상수와 스캐너의 활용

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

		Circle cone = new Circle();//객체생성
		Circle ctwo = new Circle();
		Circle cthree = new Circle();
		
//		Circle cone = new Circle(2.5f);//객체생성
//		Circle ctwo = new Circle(3.5f);
//		Circle cthree = new Circle(4f);

		System.out.println("첫번째 원의 넓이: " + cone.getCircleArea() + " 둘레: " + cone.getCircumference());
		System.out.println("두번째 원의 넓이: " + ctwo.getCircleArea() + " 둘레: " + ctwo.getCircumference());
		System.out.println("첫번째 원의 넓이: " + cthree.getCircleArea() + " 둘레: " + cthree.getCircumference());

	}

}
/*
 * 생성자에서 float 반지름을 입렵받는다 
 * 파이값은 final static float필드로 공유한다
 * public float getCircumference();원둘레
 * public float getCircleArea();원넓이
 * 객체는 3개를 만들어서 메인에서 사용해 보아요
 */
public class Circle {
	private final static float pi = 3.141f;
	private float rd;
	private static Scanner sc= new Scanner(System.in);
	
	public Circle() {
		System.out.println("반지름입력");
		rd=sc.nextFloat();
	}
	
	public Circle(float rd){// 메인클래스에서 받아와야 할 변수 값 정의, 개짓하지마
		this.rd = rd;
		}
	
		public float getCircumference() {
			return rd*2*pi;
		}
		public float getCircleArea() {
			 return rd*rd*pi;
		}
}

'java' 카테고리의 다른 글

Java/ 상속  (0) 2020.02.10
Java/ String의 개념과 비교  (0) 2020.02.10
Java/ 클래스간의 상호관계  (0) 2020.02.10
Java/Class exc/클래스 응용  (0) 2020.01.28
Java/Def of Class/클래스정의  (0) 2020.01.28

<클래스와 클래스간의 상호관계>
요구사항 : "나는 과일장수에게 사과 2개를 구매했다." 를 객체지향 프로그래밍으로 묘사하라

 

1) MVC 

Model : 데이터, 데이터 제어
View : 화면, 사용자와 대화
Controller : Model, View를 중간 제어, 업무 컨트롤

2) 명사/동사분류법
    명사 : 클래스, 필드
    동사 : 클래스, 메서드
    
- 명사 : 나, 과일장수, 사과
- 동사 : 구매했다.


- 클래스의 대상 : 나, 과일장수
- 필드 : 사과 (2개) 
- 메서드 : 구매했다.

 

 

 

- 필드는 메서드를 통해 간접접근하는 것이 원칙
- 필드는 여러 메서드에서 사용하게 되는데 외부에서 필드에 자유롭게 접근하게되면 관련 메서드들이 모두 오작동할 위험이 있기 때문에 메서드의 매개변수와 return값을 통해 간접 접근한다.

- 필드초기화 작업시 별도 초기화 함수를 사용하는 것의 단점

1. 초기화 함수가 여러번 호출되면 중간의 값이 사라질 수 있다.
2. final필드는 초기화 메서드에서는 초기화할 수 없다.
 
→ 그래서 초기화 메서드 대신 "생성자"를 사용하도록 한다.

 

- 생성자

필드의 초기화와 초기동작 설정을 위해 만들어졌다.
final 필드를 초기화하는 것이 가능하다.

 

 

public class FruitMain {
	public static void main(String[] args) {
		//객체가 만들어 질 때, 생성자가 호출됨
		FruitSeller seller = new FruitSeller(0, 20, 1000);//괄호안의 값들이 생성자의 변수값에 전달.
		FruitBuyer buyer = new FruitBuyer(10000, 0);
		
		
//		객체의 참조값은 스택에 있는 변수에 저장되고
//		참조값을 jvm에 의해서 힙에 있는 객체 실체를 가리키게 된다.
		System.out.println(seller);
		System.out.println(buyer);
		
		// 상호작용(객체간의 메시지 전송/수신)
		// 둘중에 어느 것으로 표현해도 좋다.
		// 구매했다
		// 상대 객체의 기능을 사용하고 싶으면
		// 상대 객체의 참조변수를 매개변수로 해서 가리키게 한다
		// 그리고 메서드 내부에서 상대의 메서드를 호출한다
		buyer.buyApple(seller, 2000);
		//seller.saleApple(buyer, 2000);
		
		seller.showSaleResult();
		buyer.showBuyResult();
	}
}
//변수의 상수화 - final

public class FruitSeller {// 생성자
	private int numOfApple; // 사과 개수
	private int saleMoney; // 판매 금액
	private final int APPLE_PRICE; // 사과 가격

	// 판매하다
	public int saleApple(int money) {
		int num = money / APPLE_PRICE;
		numOfApple -= num;
		saleMoney += money;
		return num;
	}

	//생성자
	//final필드를 초기화 시킬 수 있다.
	public FruitSeller(int money, int appleNum, int price) {
		saleMoney = money;
		numOfApple = appleNum;
		APPLE_PRICE = price;
	}

	// 판매결과
	public void showSaleResult() {
		System.out.println("***과일 장수의 현재 상황***");
		System.out.println("남은 사과: " + numOfApple);
		System.out.println("판매 수익: " + saleMoney);
	}
}
public class FruitBuyer {
	private int myMoney;	// 보유 금액
	private int numOfApple;	// 사과 개수
	
	//객체가 생성될때 자동으로 호출되는 메서드: 생성자
	public FruitBuyer(int money, int appleNum){
		myMoney=money;
		numOfApple=appleNum;
	}
	
	
	// 메시지 전송(buyer->seller)
	// 상대방의 객체의 메서드를 호출하는 것을 
	// 객체지향에서는 메시지 전송(상호작용)
	public void buyApple(FruitSeller seller, int money) {
		numOfApple += seller.saleApple(money);
		myMoney -= money;
	}
	public void showBuyResult() {
		System.out.println("***과일 구매자의 현재 상황***");
		System.out.println("현재 잔액: " + myMoney);
		System.out.println("사과 개수: " + numOfApple);
	}
	
}

'java' 카테고리의 다른 글

Java/ String의 개념과 비교  (0) 2020.02.10
Java/ Static의 개념과 응용  (0) 2020.02.10
Java/Class exc/클래스 응용  (0) 2020.01.28
Java/Def of Class/클래스정의  (0) 2020.01.28
Java/Recursion/재귀호출  (0) 2020.01.28

ex1

public class Star {
	public static void printStar(int num) {
		// 세로 행
		for(int i=0;i<num;i++) {
			// 가로 열
			for(int j=0;j<=i;j++) {
				System.out.print("*");
			}
			System.out.println();
		}
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while(true) {
			System.out.println("별찍기 숫자 입력");
			int num = sc.nextInt();
			if(num == -1)
				break;
			printStar(num);
			System.out.println();
		}
		
		sc.close();
	}
}
별찍기 숫자 입력
5
*
**
***
****
*****

 

 

 

ex2

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

		while (true) {
			System.out.println("다이아몬드 숫자 입력");
			int num = sc.nextInt();
			if (num == -1) {
				System.out.println("종료합니다~");
				break;
			}
			int middlePt = num / 2; // 중앙위치
			// 세로행만큼 아래로 개행
			for (int i = 0; i < num; i++) {
				// 가로열의 이동
				for (int j = 0; j < num; j++) {
					if (i <= middlePt) {
						if (j >= middlePt - i && j <= middlePt + i)
							System.out.print("*");
						else
							System.out.print(" ");
					} else { // 세로행이 중앙보다 초과
						if (j >= middlePt - (num - i - 1) && j <= middlePt + (num - i - 1))
							System.out.print("*");
						else
							System.out.print(" ");
					}
				}
				System.out.println();
			}
		}
		sc.close();
	}
}
다이아몬드 숫자 입력
7
   *   
  ***  
 ***** 
*******
 ***** 
  ***  
   *