메모장에서 shift + home(번호키7번) 하면 그 줄 전체 선택
과일장수 클래스 - 인스턴스 변수 = 사과값, 사과개수, 가지고 있는 돈
메소드 - 인스턴스 변수를 초기화 한다, 구매자에게 돈을 받으면 사과를 건네준다, 현재 자신의 상태를 출력.
구매자 클래스 - 인스턴스 변수, 사과개수, 가지고 있는 돈
메소드 - 인스턴스 변수를 초기화 한다, 과일장수에게 돈을 주고 사과를 받는다, 현재 자신의 상태를 출력.
과일메인 클래스 - 사과장수 두명을 만든다.
과일장수 1 은 사과하나의 값은 2000 원이고 사과를 50 개 들고 있고 그리고 가진돈은 50000원이다.
과일장수2 는 사과하나의 값은 1000원이고 사과를 100개를 들고 있고 그리고 가진돈은 100000원이다.
구매자는 20000원의 돈을 가지고 있으며 처음에는 사과가 하나도 없다.
2000원짜리 사과 3개와 1000원짜리 사과 5개를 구매한다.
우선은 정확히 자신이 사고싶은 만큼의 돈을 넘겨주고 거스름돈은 없는 걸로 하자.
사과 구매후 3명(과일장수, 구매자)의 상태를 출력한다.
this.> 인스턴스 자기 자신
class FruitSeller { // 멤버 변수 - 사과장수
int price; // 가격을 상수로 지정하고싶어도 밑에 내용참고
int numOfApples;
int money;
public void initFruitSeller(int price, int numOfApples, int money) {
this.price = price; // 메소드 내에서는 상수 초기화가 불가능
this.numOfApples = numOfApples;
this.money = money;
}
public int sell(int money) { // 돈을 받으면 사과를 건냄 > 받을 돈 지역변수 생성
int num = money / price;
this.money += money; // 사과 장수가 가지고있는 돈에 고객에게 받은돈
this.numOfApples -= num;
return num;
}
public void printCS() { // 자신의 상태 출력
System.out.println("사과 가격 " + price);
System.out.println("돈 " + money);
System.out.println("사과 개수 " + numOfApples);
}
} // 과일 장수 클래스 끝
class Buyer { // 구매자
int numOfApples;
int money;
public void initBuyer(int money) { // 구매자는 처음에 사과개수x이므로
this.money = money;
this.numOfApples = 0; // 원래 초기 기본값으로 0인데 명시적으로 보기위해
}
public void printCS() { // 상태 출력 메소드
System.out.println("돈 " + money);
System.out.println("사과 개수 " + numOfApples);
}
public void buy(FruitSeller seller, int money) {
this.money -= money; // this는 내가 가지고 있는돈, 다른건 줄 돈
numOfApples += seller.sell(money); // 넘겨 받은 사과 추가
}
} // 구매자 클래스 끝
class FruitMain {
public static void main(String[] args) {
FruitSeller seller1 = new FruitSeller(); // 과일 장수 1
seller1.initFruitSeller(2000, 50, 50000);
FruitSeller seller2 = new FruitSeller(); // 과일 장수 2
seller2.initFruitSeller(1000, 100, 100000);
Buyer buyer = new Buyer();
buyer.initBuyer(20000); // 고객 가지고있는 돈
buyer.buy(seller1, 6000); // 고객이 과일장수1에게 3개 구매
//buyer객체의 buy메소드 에 seller1, 6000대입해 호출
seller1.printCS();
System.out.println("======================");
seller2.printCS();
System.out.println("========================");
buyer.printCS();
}
}

그런데 이렇게 하면 고객이 장수1,2번에게 구매한 값이 한번에 나오는게 아니라 각각 따로해야해서 잘못된 식
//시나리오
//과일 장수 2명 = 객체 2개
//-멤버 변수 생성 = 사과 개수, 사과 가격, 가지고 있는 돈
//-메소드 = 변수 초기화 , 돈을 받으면 사과를 건네는, 결과 출력
//구매자 클래스
//- 멤버 변수 = 사과 개수, 가지고 있는 돈
//- 메소드 = 변수 초기화, ``, ``
class Fruit{ //과일 장수
int num, price, money;
public void initFr(int num, int price, int money){
this.num = num;
this.price = price;
this.money = money;
}
public void calculateFr(){
this.num -= cnum //사과를 팔고 남은 사과 개수
this.price += (cnum * price); //사과의 개수 만큼 돈을 받음
}
public void printFr(){
//System.out.println(
System.out.println("벌어들인 돈 : " + price);
System.out.println("남은 사과 개수 : " + num);
}
}
class Customer{ //고객
int cnum, cmoney;
public void initCu(int cnum, int cmoney){
this.cnum = cnum; //사과를 몇개 살것인지
this.cmoney = cmoney; //가지고 있는 돈이 얼만지
}
public void calculateCu(){
this.cnum += cnum; //사과를 산 후의 사과 개수
this.cmoney -= cnum * price; //사과를 산 후 남은 돈
}
public void printCu(){
System.out.println("구매한 사과의 개수 : " + cnum);
System.our.println("구매 후 남은 돈 : " + cmoney + "원");
}
}
class FruitMain{ //과일 메인 클래스
public static void main(String[]args){
Fruit f1 = new Fruit(); //사과장수 1
Fruit f2 = new Fruit(); //사과장수 2
Customer c1 = new Customer(); //고객
f1.initFr(50, 2000, 50000);
f1.calculateFr();
//f1.printFr();
f2.initFr(100, 1000, 100000);
f2.calculateCu();
//f2.printFr();
c1.initCu
class Fruiter
{
int price,fcnt,fmoney;
public void fruiterDefine(int price,int fcnt,int fmoney)
{
this.price = price;
this.fcnt = fcnt;
this.fmoney = fmoney;
}
public int fruiterSell(int cnt)
{
fcnt = fcnt-cnt;
fmoney = fmoney+price*cnt;
return price*cnt;
}
public void fruiterState()
{
System.out.println("사과장수");
System.out.println("가지고 있는 사과 갯수 : " +fcnt);
System.out.println("현재 소지금 : " +fmoney);
}
}
class Customer
{
int cnt,cmoney;
public void customerDefine(int cmoney)
{
this.cmoney = cmoney;
}
public void customerBuy(Fruiter seller,int cnt)
{
cmoney -= seller.fruiterSell(cnt);
this.cnt += cnt;
}
public void customerState()
{
System.out.println("고객");
System.out.println("가지고 있는 사과 갯수 : " +cnt);
System.out.println("현재 소지금 : " +cmoney);
}
}
class FruitMain
{
public static void main(String[] args)
{
Fruiter f1 = new Fruiter();
Fruiter f2 = new Fruiter();
Customer buyer = new Customer();
f1.fruiterDefine(2000,50,50000);
f2.fruiterDefine(1000,100,100000);
buyer.customerDefine(20000);
buyer.customerBuy(f1,0);
buyer.customerBuy(f2,0);
f1.fruiterState();
f2.fruiterState();
buyer.customerState();
}
}
class FruitSeller {
int num, price, money;
public void initFruitSeller(int num, int price, int money) {
this.num = num;
this.price = price;
this.money = money;
}
public int sell(int money) { // 돈을 받으면 사과를 건네기
int temp = money / price; // 고객에게 넘겨야할 사과 개수를 구해서 변수에 저장하는 문장
this.money += money;
this.num -= temp; //가지고있는 사과 개수에서 고객에게 준 사과 개수를 빼는 문장
return temp; //고객에게 준 사과의 개수를 return > 고객 클래스의Buy메소드로 반환하기 위함(그래야 고객이 사과를 받을 수 있기 때문이다.
}
public void printCS() {
System.out.println("사과의 개수 : " + num);
System.out.println("사과의 가격 : " + price);
System.out.println("현재 가지고 있는 돈 : " + money);
System.out.println("==============================");
}
} // 과일 장수 클래스 끝
class Buyer {
int num, money;
public void initBuyer(int money) { // 현재 가지고 있는 돈과 사과
this.money = money;
this.num = 0;
}
public void buy(FruitSeller seller, int num) { // 돈을 주고 사과를 받기
this.num += num;
this.money -= seller.sell(money); // ?
}
public void printCS() {
System.out.println("현재 사과의 개수 : " + num);
System.out.println("현재 남은 돈 : " + money);
}
} // 구매자 클래스 끝
class FruitSellerMain {
public static void main(String[] args) {
FruitSeller f1 = new FruitSeller(); // 사과장수1
FruitSeller f2 = new FruitSeller(); // 사과장수2
Buyer b2 = new Buyer(); // 구매자
f1.initFruitSeller(50, 2000, 50000);
f2.initFruitSeller(100, 1000, 100000);
b2.initBuyer(20000);
b2.buy(f1, 3);
b2.buy(f2, 5);
f1.printCS();
f2.printCS();
b2.printCS();
}
}
}
이 식은 과일장수들과 손님의 남은 돈, 사과 개수의 출력이 올바르지 않다.
그 이유는 buyer 의 buy이 문장이 올바르지 않기 때문이다
돈을 주고 사과를 넘겨받아야 하는데 반대로 사과는 그냥 받고 돈을 넘겨주고있다..
마찬가지로 main메소드에서 출력할 때 b2.buy에서 f1을 호출 후 원하는 사과의 개수가 아니라 사용자가 직접 계산해서 입력해야한다.
장수1한테 3개면 6000을 입력해야하고, 장수2한테 5개면 5000을 입력해야한다.
class AAA{
}
class BBB{
}
classABMain{
public static void main(String[]args){
AAA aaa = new AAA();
BBB bbb = new BBB();
AAA aa = new BBB(); //이 문장은 오류
BBB b2 =new AAA(); //이 문장도 오류
}
}
class AAA{
public void hi(int hahaha)
}
class BBB{
}
classABMain{
public static void main(String[]args){
AAA aaa = new AAA();
BBB bbb = new BBB();
aaa.hi(3.14); //문장 오류 - 자료형이 달라서
aaa.hi(aaa);// 오류 - aaa의 객체 주소값을 전달하려해서 자료형도 AAA가 되어야한
}
}
aaa의 객체 주소값을 전달하려해서 자료형도 AAA가 되어야한다.
class는 설계도, 객체는 class를 통해 만들어내는 결과

a1 = AAA 객체의 주소번지를 가지고있는 참조 변수
a1 = a2; 면 a1에 a2의 AAA번지 주소값이 대입되므로 a1도 2000번지의 주소값을 가지게된다. > 그러면 1000번지 메모리는 언젠가 소멸된다.(c언어는 메모리 누수가 발생 , 자바는 자동으로 가비지콜렉터 실행)
AAA a1 = new AAA();
AAA a2 = new AAA();
BBB b1 = new BBB();
a1 = a2; //가능
a1 = b1; //불가능 객체 주소값이 달라서
String name;
int age;
String sex;
public void initPerson(String name,int age,String sex){
this.name = name;
this.age = age;
this.sex = sex;
}
public void whoAmI(){
System.out.println("저의 이름은 " + name + " 이고 " + "나이는 " + age + " 입니다 " );
System.out.println("성별은 " + sex + "입니다);
}
class MainClass{
public static void main(String[]args){
Person man = new Person();
man.initPerson("홍길동", 30 , "남자");
man.whoAmI();
}
}
String name = "홍길동" > name이라는 참조 변수 안에 문자열 저장생성자는 new연산자와 같이 사용되어 클래스로부터 객체를 생성할 때 호출되어 객체의 초기화를 담당한다.
멤버 변수 초기화 > 생성자
생성자를 실행 x > 클래스로부터 객체를 만들 수 x
new연산자에 의해 생성자가 실행되면 힙 영역에 객체 생성 > 객체의 주소가 리턴되는데, 리턴된 객체의 주소는 클래스 타입 변수에 저장되어 객체에 접근할때 이용된다.
클래스 이름과 생성자의 이름은 대소문자 하나까지 똑같아야 한다.
메소드 내 (객체)에는 생성자를 가질 수 없다 > 클래스 내에서 하나 이상 존
생성자는 반환하는 값이 없고 반환하는 값을 선언(정의)해서는 안된다.
int, boolean등을 사용할 필요 x
public class Car{
//필드
String company = "Audi";
String modl = "A8";
String color = "black";
int maxSpeed = 400;
int speed;
//생성자
Car1(String color, int cc){
public static void main(String[]args){
Car1 myCar = new Car1("검정", 3000);
//Car1 myCar = new Car1(); 기본 생성자를 호출할 수 없다.
}
식별자를 만들 때 식별자의 접두어로 자료형을 표시하는 방법
요즘엔 잘 사용 안함/- 사용) 인터페이스명
int age;
age = 10;
age가 어떤 자료형인지 꼭 알고 있어야함 그러나 다시 자료형을 찾으러 가야해서 가독성이 떨어짐
int int_age;
int iAge;
int iage;
int intAge; // => 이런식으로해서 이렇게 붙여 쓸 수 있음
그러나 요즘에는 커서만 올려두면 무슨 자료형인지 알 수 있어 잘 사용하지 않음
식별자의 첫문자를 대문자 표기 + 나머지 문자를 소문자 표기
2개 이상의 합성어 > 각 단어의 첫문자를 대문자 표기
사용) 클래스명 (자바 한정)
int weight; > int Weight; // 파스칼 표기법
int englishscore; // 연달아 대소문자 없이 쓰면 가독성이 떨어짐
식별자의 첫문자를 소문자 표기 + 나머지 문자를 소문자 표기
2개 이상의 합성어 > 각 단어의 첫문자를 대문자 표기
사용) 변수명, 메소드명
int mathscore;
int MathScore; //파스칼 표기법 - 변수에 적용하지는 않음 > 좋지 않은 적용
int mathScore; //캐멀 표기법 - 처음 시작하는 문자는 소문자이지만 다음 단어는 대문자 > 자바에서 가장 좋은 적용
전부 소문자로 표기
합성어 > 각 단어를 '_' 로 연결
사용) 마음대로~
int englishScore; //캐멀- 왠만하면 캐멀 쓰는게 좋지만
int english_score; // 스네이크 -이것도 나쁘지 않음
전부 소문자로 표기
합성어 > 각 단어를 '-'로 연결
HTML, CSS > 자주 사용
어린아이가 소유하고 있는 구슬의 개수 정보를 담을 수 있다.
놀이를 통한 구슬의 주고받음을 표현하는 메소드가 존재한다.
어린이의 현재 보유자산(구슬의 수)을 출력하는 메소드가 존재한다.
위의 두 번째 조건은 두 아이가 구슬치기를 하는 과정에서 구슬의 잃고 얻음을 의미하는 것이다.(이 문제 마지막까지 읽어야 필요한 메소드가 무엇인지 정확히 파악할 수 있다.) 위의 조건을 만족하는 클래스를 정의하였다면, 다음 조건을 만족하는 인스턴스를 각각 생성하자.
어린이1의 보유자산 -> 구슬 15개
어린이2의 보유자산 -> 구슬 9개
인스턴스의 생성이 완료되면 다음의 상황을 main 메소드 내에서 시뮬레이션 하자.
"1차 게임에서 어린이1은 어린이2의 구슬 2개를 획득한다."
"2차 게임에서 어린이2는 어린이1의 구슬 7개를 획득한다."
마지막으로 각각의 어린이가 보유하고 있는 구슬의 수를 출력하면서 프로그램을 종료한다.
class Child
{
String name; //어린이 이름 저장
int marbles;
public Child(String name, int marbles)
{
this.name = name;
this.marbles = marbles;
}
public void win(Child child, int marbles) //잃은 친구한테 구슬 달라고 요청 - main메소드에서 누가 이겼는지 누구의 돈을 빼앗아 올건지 입력하기때문에 Child자료형을 넣어야하는것
{
this.marbles += child.lose(marbles);
}
public int lose(int marbles)
{
if(this.marbles < marbles) //이 if문은 혹여나 가지고있는 구슬 수보다 줘야하는 구슬수가 더 많으면 0을 출력하기 위한 구문이다.
{
int temp = this.marbles;
this.marbles = 0;
return temp;
}
this.marbles -= marbles;
return marbles;
}
public void printCS()
{
System.out.println(name + " " + marbles);
}
}
class ChildMain
{
public static void main(String[] args)
{
Child child1 = new Child("어린이1", 15);
Child child2 = new Child("어린이2", 9);
child1.win(child2, 2);
child1.printCS();
child2.printCS();
System.out.println("=================");
child2.win(child1, 7);
child1.printCS();
child2.printCS();
}
}
main메소드에서 child1.win(child2, 2); 문장은 child1주소의 win을 호출한것이다.
child1주소의 win의 child와marble은 참조 변수로 생성되고, child에는 child1이라는 주소가 들어가고, marbles에는 2가 들어간다.
문장 속으로 들어오면, this.marbles는 child1주소인 marbles로 15가 들어가있는 상태이고, 복합 연산자 옆에 child.lose(marbles)는 lose메소드를 호출하기 때문에 lose메소드로 이동한다
위에서 참조변수 marbles 값에 2가 있는상태에서 lose메소드로 왔으므로, lose메소드의 파라미터에도 2가 들어가 if문이 수행된다.
그렇다면 child2의 marbles는 9이고, 참조변수의 marbles는 2이므로 if문은 수행되지 않고, child2의 marbles에서 참조변수marbles의 값을 뺀 후 그 값을 return한다. 그럼 그 값이 win메소드로 올라가 child1의 marbles와 더해지는것이다.
class BeadsPlay{ //멤버 변수
int originb, getb, lostb;
public BeadsPlay(int originb, int getb, int lostb){ //초기화
this.originb = originb;
this.getb = getb;
this.lostb = lostb;
}
public int game(int getb){ //구슬을 잃고 얻음 > 얻은 개수
int num = getb + originb; //현재 구슬의 총개수
this.lostb = originb - lostb;
this.getb += getb;
return num;
//이런식의 식은 안됌. 식은 주고받음이 있어야하므로
}
public void printCS(){ // 어린이의 현재 보유자산 출력
System.out.println("총 나의 구슬 수 : " + getb);
//System.out.println(getb + originb + lostb);
}
}
class Boy{ //이거 자체를 만들 필요는 없는것이였다.
//class는 설계도고, 객체는 이 class를 이용해서 결과값을 내는것이기때문에 boy는 객체로 생성해서 프로그래밍하면 됐던것
int boriginb, bgetb;
public Boy(int boriginb, int bgetb){ //초기화
this.boriginb = boriginb;
this.bgetb = bgetb;
}
public void
class BeadsPlayMain{
public static void main(String[]args){
System.out.println("1차 게임에서 어린이1은 어린이2의 구슨 2개를 획득한다.");
System.out.println("2차 게임에서 어린이 2는 어린이1의 구슬 7개를 획득한다");
BeadsPlay boy1 = new BeadsPlay(15);
BeadsPlay boy2 = new beadsPlay(9);
class에 초기화하는 메소드와 이기고 지는 메소드를 만들고 남자아이 객체 두개 생성해서 하면 됐던것
나는 boy메소드를 따로 생성해야 한다고 잘못 생각.
그래서 위 정답 코드에는 String 클래스로 알아보기도 쉽게 선언해놓은