접근제어

 

public : 클래스 외부에서 접근이 가능하다.

 

private : 클래스 내부에서만 접근이 가능하다.

 

default : 동일 패키지에 있는 다른 클래스에서 접근 가능하다.

 

protected : 동일 패키지의 다른 클래스와 다른 패키지의 하위클래스에서도 접근 가능하다.

 


 

데이터 캡슐화

 

모든 데이터 멤버를 private으로 만들고 필요한 경우에 public한 get/set 메서드를 제공한다.

 

이렇게 하면 객체가 제공해주는 메서드를 통하지 않고서는 객체 내부의 데이터에 접근할 수가 없다.

 

이것은 data encapsulation혹은 information hiding이라고 부른다.

 


 

앞서 나왔던 프로젝트에 데이터필드와 메서드를 알맞은 지정자를 지정한 후

getter setter를 이용해 보았다.

 

package section2;

public class Term3 {
	
	private int coef;//계수
	private int exp;//차수
	
	public Term3(int c, int e) {
		coef = c;
		exp = e;
	}
	
	public int calTerm(int x) {
		return (int)(coef * Math.pow(x, exp));
	}
	
	public void printTerm() {
		System.out.print(coef + "x^" +exp);
	}
	public int getCoef() {
		return coef;
	}
	public void setCoef(int coef) {
		this.coef = coef;
	}
	public int getExp() {
		return exp;
	}
}
package section2;

public class Polynomial3 {
	
	private char name; //다항식의 이름
	private int nTerms = 0; // 항의 개수
	private Term3[] terms; //항들의 배열
	
	public Polynomial3() {
		nTerms=0;
		terms = new Term3[100];
	}
	
	public Polynomial3(char name) {
		this.name = name;
		nTerms=0;
		terms = new Term3[100];
	}
	
	public char getName() {
		return name;
	}
	
	public int calcPolynomial(int x) {
		int result = 0;
		
		for (int i =0; i< nTerms; i++) {
			result += (terms[i].calTerm(x));
			}
		return result;
	}

	public void printPolynomial() {
		for(int i =0; i<nTerms; i++) {
			terms[i].printTerm();
			System.out.print("+");
		}
		System.out.println();
		
	}
	
	public void addTerm(int c, int e) {
		int index = findTerm(e);
		if(index != -1) {
				terms[index].setCoef(terms[index].getCoef() + c);
		}
		else {
			int i = nTerms-1;
			while(i >= 0 && terms[i].getExp() < e) {
				terms[i+1] = terms[i];
				i--;
			}
			terms[i+1] = new Term3(c,e);
			nTerms++;
		}
	}

	private int findTerm(int e) {
		for(int i=0;i<nTerms && terms[i].getExp() >= e;i++) {
			if(terms[i].getExp() ==e) {
				return i;
			}
		}
		return -1;
	}
}
package section2;

import java.util.Scanner;

public class code11{

	Polynomial3 polys[] = new Polynomial3 [100];
	int n = 0;
	
	public void procesCommand() {
		Scanner kb = new Scanner(System.in);
		while(true) {
			System.out.print("$ ");
			String command = kb.next();
			if(command.equals("create")) {
				char name = kb.next().charAt(0);
				polys[n] = new Polynomial3(name);
				n++;
			}
			else if(command.equals("add")) {
				char name = kb.next().charAt(0);
				int index = find(name);
				if(index==-1) {
					System.out.println("No such Polynomial exist");
				}
				else {
					int c = kb.nextInt();
					int e = kb.nextInt();
					polys[index].addTerm(c,e);
					
				}
				
			}
			else if(command.equals("calc")) {
				char name = kb.next().charAt(0);
				int index = find(name);
				if(index==-1) {
					System.out.println("No such Polynomial exist");
				}
				else {
					int x = kb.nextInt();
					int result = polys[index].calcPolynomial(x);
					System.out.println(result);
				}
				
			}
			else if(command.equals("print")) {
				char name = kb.next().charAt(0);
				int index = find(name);
				if(index==-1) {
					System.out.println("No such Polynomial exist");
				}
				else {
					polys[index].printPolynomial();
				}

			}
			else if(command.equals("exit")) {
				break;
			}
		}
		
		kb.close();

	}
	public static void main(String[] args) {
		
		code11 app = new code11();
		app.procesCommand();

	}

	private int find(char name) {
		for(int i =0;i<n;i++) {
			if(polys[i].getName() == name) {
				return i;
			}
		}
		return -1;
	}

}

 

'알고리즘 with 자바 > 자료구조' 카테고리의 다른 글

상속 2  (0) 2021.06.29
상속 1  (0) 2021.06.29
static 그리고 public 1  (0) 2021.06.28
메서드와 생성자 3  (0) 2021.06.24
메서드와 생성자 2  (0) 2021.06.24

클래스는 타입이다. 집이 아니라 집의 설계도이다. 즉 실체가 아니다!

 

따라서 클래스의 데이터 필드에 데이터를 저장할 수는 없고, 클래스의 

멤버 메서드를 실행할 수 도 없다. 왜냐하면 실체가 아니기 때문

 

new 명령으로 해당 클래스의 객체를 만든 후 , 그 객체에 데이터를 저장하고,

그 객체의 멤버 메서드를 실행하는 것이다. 

 

여기에는 하나의 예외가 존재하는데 그것이 static 멤버이다.

static 멤버는 클래스 안에 실제로 존재하며 객체에는 존재하지 않는다.

 

 그렇다면?

 

왜 메인 메서드는 반드시 static이어야 하는가?

   자바에서는 프로그램이란 클래스의 집합이다. 이 클래스라는건 설계도일뿐!

   그렇기에 static이어야 한다. main이라는 것은 시작점이기에 누군가 new로 만들어줄 수 없기때문이다.

 

왜 static 메서드에서 같은 클래스의 non-static 멤버를 액세스할 수 없는가?

   메인 함수가 포함된 클래스에서는 이때까지 static변수를 사용하였다. static메서드는 클래스 메서드이다.

   그렇기에 static멤버만 액세스가 가능!

 

다른 클래스에 속한 static 멤버는 어떻게 액세스 하는가?

   static멤버는 클래스이름.static멤버 이런식으로 액세스한다.

 

static 메서드/필드의 용도는?

   1. static의 필수적인 경우는 메인 메서드이다.

   2. 상수, 혹은 클래스 당 하나만 유지하고 있으면 되는값

   3. 순수하게 기능만으로 정의되는 메서드, 대표적인 예로는 수학 함수들.

 

앞에서 작성했던 다항식 프로그램들을 main메서드만이 static이 되도록 수정해보았다!

 

package section2;

import java.util.Scanner;

public class code11{

	Polynomial3 polys[] = new Polynomial3 [100];
	int n = 0;
	
	public void procesCommand() {
		Scanner kb = new Scanner(System.in);
		while(true) {
			System.out.print("$ ");
			String command = kb.next();
			if(command.equals("create")) {
				char name = kb.next().charAt(0);
				polys[n] = new Polynomial3(name);
				n++;
			}
			else if(command.equals("add")) {
				char name = kb.next().charAt(0);
				int index = find(name);
				if(index==-1) {
					System.out.println("No such Polynomial exist");
				}
				else {
					int c = kb.nextInt();
					int e = kb.nextInt();
					polys[index].addTerm(c,e);
					
				}
				
			}
			else if(command.equals("calc")) {
				char name = kb.next().charAt(0);
				int index = find(name);
				if(index==-1) {
					System.out.println("No such Polynomial exist");
				}
				else {
					int x = kb.nextInt();
					int result = polys[index].calcPolynomial(x);
					System.out.println(result);
				}
				
			}
			else if(command.equals("print")) {
				char name = kb.next().charAt(0);
				int index = find(name);
				if(index==-1) {
					System.out.println("No such Polynomial exist");
				}
				else {
					polys[index].printPolynomial();
				}

			}
			else if(command.equals("exit")) {
				break;
			}
		}
		
		kb.close();

	}
	public static void main(String[] args) {
		
		code11 app = new code11();
		app.procesCommand();

	}

	private int find(char name) {
		for(int i =0;i<n;i++) {
			if(polys[i].name == name) {
				return i;
			}
		}
		return -1;
	}

}

 

 

'알고리즘 with 자바 > 자료구조' 카테고리의 다른 글

상속 1  (0) 2021.06.29
static 그리고 public 2  (0) 2021.06.28
메서드와 생성자 3  (0) 2021.06.24
메서드와 생성자 2  (0) 2021.06.24
메서드와 생성자 1  (0) 2021.06.23

다각형과 점

 

입력으로 하나의 직교 다각형(모든 변이 x축 혹은 y축과 평행한 다각형)의 또 하나의 점 p가 주어질 때 그 점이 다각형의 내부에 있는지

외부에 있는지 판단하는 프로그램을 작성하라

 

입력 형식의 예 시계방향으로 꼭지점의 좌표가 주어짐

8 // 꼭지점의 개수

0 0 //첫번째 꼭지점 x,y 좌표

16 0

16 18

10 18

10 6

6 6

6  12

0 12 //마지막 꼭지점의 x,y 좌표

7 7 //테스트할 점 p의 좌표


내부 / 외부 검사

 

점에서 시작하여 한 방향으로 무한히 뻗어가는 아무 직선이나 하나 그어서

그것이 다각형의 변과 짝수 번 교차하면 외부, 홀수번 교차하면 내부에 있다.

 

문제는 그은 직선이 겹치게된다면 ???

꼭지점의 좌표값은 모두 짝수, 검사할 점 좌표값은 홀수로 가정한다.

 

package section2;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class code10 {

	public static void main(String[] args) {
		
		try {
			Scanner in = new Scanner(new File("data.txt"));
			int n = in.nextInt();
			OrthPolygon thePolygon = new OrthPolygon(n);
			for(int i =0; i<n; i++)
				thePolygon.addVertex(in.nextInt(),in.nextInt());
			Mypoint2 thePoint = new Mypoint2(in.nextInt(),in.nextInt());
			in.close();
			if(thePolygon.contains(thePoint))
				System.out.println("Yes");
			else
				System.out.println("No");
		}catch(FileNotFoundException e) {
			System.out.println("No data file exists");
			System.exit(1);
		}

	}

}

 

메인 함수 클래스!

 

package section2;

public class OrthLine {
	public Mypoint2 u;
	public Mypoint2 v;
	
	public OrthLine(Mypoint2 p, Mypoint2 q){
		u =p;
		v= q;
		if(p.x>q.x || p.x==q.x && p.y>q.y)
			swap();
	}
	
	private void swap() {
		Mypoint2 tmp = u;
		u =v;
		v=tmp;
	}
	
	public OrthLine(int x, int y, int x1, int y1){
		u =new Mypoint2(x,y);
		v = new Mypoint2(x1,y1);
	}
	
	public boolean isVertical() {
		return (u.x == v.x);
	}
	
	public boolean intersects(OrthLine other) {
		if(isVertical() && !other.isVertical()) {
			return(other.u.x < u.x && other.v.x > u.x && u.y <other.u.y && v.y > other.u.y);
		}
		else if(!isVertical() && other.isVertical()) {
			return(other.u.y < u.y && other.v.y > u.y && u.x < other.u.x &&v.x > other.u.x);
		}
		else
			return false;
	}
}

선분 클래스

 

package section2;

public class OrthPolygon {
	public int n;
	public Mypoint2 [] vertices;
	
	public OrthPolygon(int k) {
		n=0;
		vertices = new Mypoint2[k];
	}
	public void addVertex(int x, int y) {
		vertices[n++] = new Mypoint2(x,y);
	}
	
	public int maxX() {
		int max = vertices[0].x;
		for(int i =0;i <n;i++) {
			if(vertices[i].x>max)
				max =vertices[i].x;
		}
		return max;
	}
	
	public boolean contains(Mypoint2 p) {
		OrthLine arrow = new OrthLine(p, new Mypoint2(maxX()+1,p.y));
		int count =0;
		for(int i =0;i<n;i++) {
			OrthLine edge = new OrthLine(vertices[i], vertices[(i+1)%n]);
			if(arrow.intersects(edge))
				count++;
		}
		return (count % 2 == 1);
	}
}

직교 다각형 클래스 

 

기하학 적인 프로젝트를 할때마다 뭔가 어렵지만 종이에 그려가며

하니 조금 수월 하였다 이부분에대해서는 아직 이해가 덜되어 

계속 읽어보며 이해를 더 해야할 것같다!!

'알고리즘 with 자바 > 자료구조' 카테고리의 다른 글

static 그리고 public 2  (0) 2021.06.28
static 그리고 public 1  (0) 2021.06.28
메서드와 생성자 2  (0) 2021.06.24
메서드와 생성자 1  (0) 2021.06.23
클래스 ,객체, 참조변수 5  (0) 2021.06.23

생성자

 

클래스 안에 그 클래스와 동일한 이름을 가지며 return 타입이 없는 특별한 메서드를 둘 수 있는데

이것을 생성자 라고 부른다.

 

생성자는 new 명령으로 객체가 생성될때 자동으로 실행된다. 주 목적은 객체의 데이터

필드의 값을 초기화하는 것이다.

 

생성자가 반드시 매개변수를 받아야하는 것은 아니다.

 

package section2;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class code09 {

	static MyRectangle2[] rects = new MyRectangle2[100];
	static int n = 0;
	
	public static void main(String[] args) {
		
		try {
			Scanner in = new Scanner(new File("data.txt"));
			
			while(in.hasNext()) {
			rects[n++] = new MyRectangle2(in.nextInt(),in.nextInt(),in.nextInt(),in.nextInt());
			}
			in.close();
		} catch (FileNotFoundException e) {
			System.out.println("no data file");
			System.exit(1);
		}
		bubbleSort();
	
		for(int i =0;i<n;i++) 
			System.out.println(rects[i].toString());
		}
	
		private static void bubbleSort() {
			for(int i = n-1;i>0;i--) {
				for(int j =0; j<i; j++) {
					if(rects[j].calArea() > rects[j+1].calArea()) {
						MyRectangle2 tmp = rects[j];
						rects[j] = rects[j+1];
						rects[j+1] = tmp;
					}
				}
			}
		}
}


 

package section2;

public class Mypoint2 {
	public int x;
	public int y;
	
	public Mypoint2(int x, int y) {
		this.x = x;
		this.y = y;
	}
}
package section2;

public class MyRectangle2 {
	public Mypoint2 lu;
	public int width;
	public int height;
	
	public MyRectangle2(int x, int y, int w, int h) {
		lu = new Mypoint2(x,y);
		width =w;
		height = h;
	}
	public int calArea() {
		return width * height;
	}
	
	public String toString() {
		return "("+lu.x + ","+ lu.y +")"+ width + " " + height;
	}
}

생성자를 이용해서 저번 code5를 수정해보았다.

 

어떤 이유때문에 사각형 하나를 표현할때 꼭지점의 좌표와 높이 너비를 이용해 표현하지 않고

대각 방향에 두 꼭지점의 좌표를 이용한다고 했을때

수정이 필요하다!

 

이전 코드였다면 표현방법을 바꿧을뿐인데

그 클래스와 다른클래스 까지 다 바꿔야만 한다.

 

지금은 해당 클래스만 바꾸면 되지만 

메인함수 클래스에서는 대부분 어떠한 것도 바꿀 필요가 없게된다!!

 

어찌되었건 코드의 수정이 적어진다!

응집도를 높이고 결합도가 높아지게 하기 위함이다

 

'알고리즘 with 자바 > 자료구조' 카테고리의 다른 글

static 그리고 public 1  (0) 2021.06.28
메서드와 생성자 3  (0) 2021.06.24
메서드와 생성자 1  (0) 2021.06.23
클래스 ,객체, 참조변수 5  (0) 2021.06.23
클래스, 객체, 참조변수 4  (0) 2021.06.22

클래스 라는 것은 관련있는 데이터들을 하나의 단위로 묶어두기 위한 것이다.

하지만 이것이 전부가 아니다.

서로 관련있는 데이터들 뿐 아니라, 그 데이타와 관련이 깊은 메서드 까지도 함께 묶어둘 수 있다.

이렇게 함으로써 코드의 응집도를 높이고 결합도를 낮출 수 있다.

 

객체란 ?

 

객체지향 프로그래밍에서 객체란 " 데이터 " + " 메서드 " 이다. 데이터는 객체의 정적 속성을

표현하고 메서드는 객체의 기능을 표현한다.

 

그렇다면 전의 예제의 함수들을 옮겨보겠다!

package section2;

public class Polynomial2 {
	
	public char name; //다항식의 이름
	public int nTerms = 0; // 항의 개수
	public Term2[] terms; //항들의 배열
	
	public int calcPolynomial(int x) {
		int result = 0;
		
		for (int i =0; i< nTerms; i++) {
			result += (terms[i].calTerm(x));
			}
		return result;
	}

	public void printPolynomial() {
		for(int i =0; i<nTerms; i++) {
			terms[i].printTerm();
			System.out.print("+");
		}
		System.out.println();
		
	}
	
	public void addTerm(int c, int e) {
		int index = findTerm(e);
		if(index != -1) {
				terms[index].coef += c;
		}
		else {
			int i = nTerms-1;
			while(i >= 0 && terms[i].exp < e) {
				terms[i+1] = terms[i];
				i--;
			}
			terms[i+1] = new Term2();
			terms[i+1].coef = c;
			terms[i+1].exp =e;
			nTerms++;
		}
	}

	public int findTerm(int e) {
		for(int i=0;i<nTerms && terms[i].exp >=e ;i++) {
			if(terms[i].exp ==e) {
				return i;
			}
		}
		return -1;
	}
}

    다항 클래스

package section2;

public class Term2 {
	
	public int coef;//계수
	public int exp;//차수
	
	public int calTerm(int x) {
		return (int)(coef * Math.pow(x, exp));
	}
	
	public void printTerm() {
		System.out.print(coef + "x^" +exp);
	}
}

항 클래스

package section2;

import java.util.Scanner;

public class code7{

	static Polynomial2 polys[] = new Polynomial2 [100];
	static int n = 0;
	
	public static void main(String[] args) {
		
		Scanner kb = new Scanner(System.in);
		while(true) {
			System.out.print("$ ");
			String command = kb.next();
			if(command.equals("create")) {
				char name = kb.next().charAt(0);
				polys[n] = new Polynomial2();
				polys[n].terms = new Term2[100];
				polys[n].name = name;
				polys[n].nTerms = 0;
				n++;
			}
			else if(command.equals("add")) {
				char name = kb.next().charAt(0);
				int index = find(name);
				if(index==-1) {
					System.out.println("No such Polynomial exist");
				}
				else {
					int c = kb.nextInt();
					int e = kb.nextInt();
					polys[index].addTerm(c,e);
					
				}
				
			}
			else if(command.equals("calc")) {
				char name = kb.next().charAt(0);
				int index = find(name);
				if(index==-1) {
					System.out.println("No such Polynomial exist");
				}
				else {
					int x = kb.nextInt();
					int result = polys[index].calcPolynomial(x);
					System.out.println(result);
				}
				
			}
			else if(command.equals("print")) {
				char name = kb.next().charAt(0);
				int index = find(name);
				if(index==-1) {
					System.out.println("No such Polynomial exist");
				}
				else {
					polys[index].printPolynomial();
				}

			}
			else if(command.equals("exit")) {
				break;
			}
		}
		
		kb.close();

	}

	private static int find(char name) {
		for(int i =0;i<n;i++) {
			if(polys[i].name == name) {
				return i;
			}
		}
		return -1;
	}

}

메인 클래스

'알고리즘 with 자바 > 자료구조' 카테고리의 다른 글

메서드와 생성자 3  (0) 2021.06.24
메서드와 생성자 2  (0) 2021.06.24
클래스 ,객체, 참조변수 5  (0) 2021.06.23
클래스, 객체, 참조변수 4  (0) 2021.06.22
클래스, 객체, 참조변수 3  (0) 2021.06.22

다항함수

 

다항함수는 항들의 합이며, 항은 계수와 지수에 의해서 정의된다. 계수는 0이 아닌 정수이고

지수는 음이 아닌 정수라고 가정한다.

 

프로그램 실행 예

$ create f // f=0을 정의한다.

$ add f 2 3 // f(x)에 2x3승 을 더한다. 따라서 f(x) = 2x3이 된다.

$ add f -1 1 // f(x) = 2x3 -x

$ calc f 2 // x=2일때 f의 값을 출력한다.

$ print f // 차수에 관한 내림차순으로 정렬하여 출력한다.

$ create g // 다른 다항함수 g를 정의한다.

$ exit //종료

 

처음에는 어떤 자료구조를 만들어 

다항함수를 표현할것인가??

 

항 들이 모여서 다항함수를 만든다!

 

package section1;

public class Term {
	
	public int coef;//계수
	public int exp;//차수
}

계수와 차수를 가지는 항 클래스 생성

 

package section1;

public class Polynomial {
	
	public char name; //다항식의 이름
	public int nTerms; // 항의 개수
	public Term[] terms; //항들의 배열
}

 

다항 클래스 생성

 

package section1;

import java.util.Scanner;

public class code6 {

	static Polynomial polys[] = new Polynomial [100];
	static int n = 0;
	
	public static void main(String[] args) {
		
		Scanner kb = new Scanner(System.in);
		while(true) {
			System.out.print("$ ");
			String command = kb.next();
			if(command.equals("create")) {
				char name = kb.next().charAt(0);
				
				polys[n] = new Polynomial();
				polys[n].terms = new Term[100];
				polys[n].name = name;
				polys[n].nTerms = 0;
				n++;
			}
			else if(command.equals("add")) {
				char name = kb.next().charAt(0);
				int index = find(name);
				if(index==-1) {
					System.out.println("No such Polynomial exist");
				}
				else {
					int c = kb.nextInt();
					int e = kb.nextInt();
					addTerm(polys[index], c,e);
					
				}
				
			}
			else if(command.equals("calc")) {
				char name = kb.next().charAt(0);
				int index = find(name);
				if(index==-1) {
					System.out.println("No such Polynomial exist");
				}
				else {
					int x = kb.nextInt();
					int result = calcPolynomial(polys[index], x);
					System.out.println(result);
				}
				
			}
			else if(command.equals("print")) {
				char name = kb.next().charAt(0);
				int index = find(name);
				if(index==-1) {
					System.out.println("No such Polynomial exist");
				}
				else {
					printPolynomial(polys[index]);
				}

			}
			else if(command.equals("exit")) {
				break;
			}
		}
		
		kb.close();

	}

	private static int calcPolynomial(Polynomial p, int x) {
		int result = 0;
		
		for (int i =0; i<p.nTerms; i++) {
			result += calTerm(p.terms[i], x);
			}
		return result;
	}

	private static int calTerm(Term term, int x) {
		return (int)(term.coef * Math.pow(x, term.exp));
	}

	private static void printPolynomial(Polynomial p) {
		for(int i =0; i<p.nTerms; i++) {
			printTerm(p.terms[i]);
			System.out.print("+");
		}
		System.out.println();
		
	}

	private static void printTerm(Term term) {
		System.out.print(term.coef + "x^" +term.exp);
		
	}

	private static void addTerm(Polynomial p, int c, int e) {
		int index = findTerm(p,e);
		if(index != -1) {
			p.terms[index].coef += c;
		}
		else {
			int i = p.nTerms-1;
			while(i >= 0 && p.terms[i].exp < e) {
				p.terms[i+1] = p.terms[i];
				i--;
			}
			p.terms[i+1] = new Term();
			p.terms[i+1].coef = c;
			p.terms[i+1].exp =e;
			p.nTerms++;
		}
	}

	private static int findTerm(Polynomial p, int e) {
		for(int i=0;i<p.nTerms && p.terms[i].exp >=e ;i++) {
			if(p.terms[i].exp ==e) {
				return i;
			}
		}
		return -1;
	}

	private static int find(char name) {
		for(int i =0;i<n;i++) {
			if(polys[i].name == name) {
				return i;
			}
		}
		return -1;
	}

}

디테일한 완성도가 떨어지는 코드라서 몇 가지 수정해야할 부분을 수정할 예정이다.

'알고리즘 with 자바 > 자료구조' 카테고리의 다른 글

메서드와 생성자 2  (0) 2021.06.24
메서드와 생성자 1  (0) 2021.06.23
클래스, 객체, 참조변수 4  (0) 2021.06.22
클래스, 객체, 참조변수 3  (0) 2021.06.22
클래스, 객체, 참조변수 2  (0) 2021.06.21

평면상에 좌표축에 평행한 n개의 직사각형에 과한 데이터를 입력 받은 후 면적이 작은 것부터 큰 것 순으로 정렬하여

출력하는 프로그램을 작성하라

 

입력 파일의 형식: 

0 1 2 4

1 4 7 8

4 3 12 9

8 18 11 30

5 10 6 11

 

맨 앞 두정수가 좌상단의 꼭지점 좌표!

세번째 정수는 너비

네번째는 높이이다.

 

package section1;

public class Mypoint1 {
	public int x;
	public int y;
}

좌표를 저장하는 클래스

package section1;

public class MyRectangle1 {
	public Mypoint1 lu;
	public int width;
	public int height;
}

사각형 정보를 저장할 클래스

 

 

 

package section1;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class code05 {

	static MyRectangle1[] rects = new MyRectangle1[100];
	static int n = 0;
	
	public static void main(String[] args) {
		
		try {
			Scanner in = new Scanner(new File("data.txt"));
			
			while(in.hasNext()) {
			rects[n] = new MyRectangle1();
			rects[n].lu= new Mypoint1();
			rects[n].lu.x = in.nextInt();
			rects[n].lu.y = in.nextInt();
			rects[n].width = in.nextInt();
			rects[n].height = in.nextInt();
			n++;
			}
			in.close();
		} catch (FileNotFoundException e) {
			System.out.println("no data file");
			System.exit(1);
		}
		bubbleSort();
	
		for(int i =0;i<n;i++) 
			System.out.println(rects[i].lu.x + " "+ rects[i].lu.y + " "+rects[i].width + " " + rects[i].height);
		}
		private static void bubbleSort() {
			for(int i = n-1;i>0;i--) {
				for(int j =0; j<i; j++) {
					if(calArea(rects[j]) > calArea(rects[j+1])) {
						MyRectangle1 tmp = rects[j];
						rects[j] = rects[j+1];
						rects[j+1] = tmp;
					}
				}
			}
		}
		public static int calArea(MyRectangle1 r) {
			return r.width * r.height;
		}
}


 항상 객체안에 내용을 건들때 자꾸 new로 생성을 해주고 건들어야한다는 것을 

까먹는다.. 객체 안에 객체가 들어있기때문에 

rects[n] = new MyRectangle1();
rects[n].lu= new Mypoint1();

이부분에서 약간 애를 먹었다.

'알고리즘 with 자바 > 자료구조' 카테고리의 다른 글

메서드와 생성자 1  (0) 2021.06.23
클래스 ,객체, 참조변수 5  (0) 2021.06.23
클래스, 객체, 참조변수 3  (0) 2021.06.22
클래스, 객체, 참조변수 2  (0) 2021.06.21
클래스 , 객체, 참조변수 1  (0) 2021.06.21
package section1;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class code03 {
	
	static Person1 members[]= new Person1[100];
	static int n = 0;

	public static void main(String[] args) {
		try {
			Scanner in = new Scanner(new File("data.txt"));
			while(in.hasNext()) {
				String name = in.next();
				String number = in.next();
				
				members[n] = new Person1();
				members[n].name=name;
				members[n].number=number;
				n++;
			}
			
			
			in.close();
		} catch (FileNotFoundException e) {
			System.out.println("No file");
		}
		
		bubleSort();
		
		for(int i=0; i<n; i++) {
			System.out.println(members[i].name + " "+ members[i].number);
		}
	}

	private static void bubleSort() {
		
		for(int i=n-1;i>0;i--) {
			for(int j =0; j<i; j++) {
				if(members[j].name.compareTo(members[j+1].name) > 0 ) {
					Person1 tmp = members[j];
					members[j] = members[j+1];
					members[j+1] = tmp;
				}
			}
		}
		
	}

}

저번시간의 코드를 살짝수정하여 버블정렬하는 코드를 작성했다

클래스를 사용하기 전에는 정렬시에 이름따로 번호따로 정렬을 하는 코드를 짰었는데

클래스를 사용하니 객체배열 각각의 참조변수에 주소값을 바꿔주어 이용하여 관련있는

데이터를 한번에 가르키게 될 수 있게 되엇다. 

 

new명령어로 만들게 되면 고유한 이름을 가질 수 없기때문에

객체만 있어서는 객체를 사용할 수 없다 그래서 참조 변수가 필요하다

 

클래스, 참조변수, 객체에 대한 이해가 잘 되게 되었다!

 


인덱스 메이커 프로그램의 수정

어떠한 텍스트 파일이 있다면 그 파일안에의 단어추출과 단어의 등장 빈도를 구해주는 프로그램을

클래스를 사용하여 리팩토링 해보았다!

 

 

package section1;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class IndexMaker {
	
	static Item items[] = new Item[100000];
	static int n = 0;
	
	public static void main(String[] args) {
		
		Scanner kb = new Scanner(System.in);
		while(true) {
			System.out.print("$ ");
			String command = kb.next();
			if(command.equals("read")) {
				String filename =kb.next();
				makeIndex(filename);
			}
			else if(command.equals("find")) {
				String str = kb.next();
				int index = findWord(str);
				if(index > -1) {
					System.out.println("The word " + items[index].word +" appears " + items[index].count + " times.");
				}
				else
					System.out.println("The word " + str +" dose not appears ");
			}
			else if(command.equals("saveas")) {
				String filename = kb.next();
				saveAs(filename);
			}
			else if(command.equals("exit")) {
				break;
			}
			
			
		}
		kb.close();
		
		for(int i=0; i<n; i++) {
			System.out.println(items[i].word+" "+items[i].count);
		}
	}
	static void makeIndex(String filename){
		
		try {
			Scanner inFile = new Scanner(new File(filename));
			while(inFile.hasNext()) {
				String str = inFile.next();
				
				String trimed = triming(str);
				if(trimed != null) {
					String t = trimed.toLowerCase();
					addWord(t);
				}
			}
			inFile.close();
		} catch (FileNotFoundException e) {
			System.out.print("No File");
			return;
		}
	}
	static String triming(String str) {
		
		int i =0, j = str.length()-1;
		while(i <str.length() && !Character.isLetter(str.charAt(i)))
			i++;
		while(j<str.length() && !Character.isLetter(str.charAt(j)))
			j--;
		
		if(i>j)
			return null;
		return str.substring(i,j+1);
	}
	static void addWord(String str) {
		int index = findWord(str);
		if(index != -1) {
			items[index].count++;
		}
		else {
			int i =n-1;
			for(;i>=0  && items[i].word.compareToIgnoreCase(str)>0;i--) {
				
				items[i+1] = items[i];
				i--;
			}
			items[i+1] = new Item();
			items[i+1].word = str;
			items[i+1].count =1;
			n++;
		}
		
	}
	static int findWord(String str) {
		for(int i=0;i<n;i++) 
			if(items[i].word.equalsIgnoreCase(str)) {
				return i;
			}
		return -1;
	}
	static void saveAs(String fileName) {
		try {
			PrintWriter outFile = new PrintWriter(new FileWriter(fileName));
			for(int i =0;i<n;i++) {
				outFile.println(items[i].word + " " + items[i].count);
			}
			outFile.close();
		} catch (IOException e) {
			System.out.println("save failed");
			return;
		}
	}
}

 중요한 것은 역시 객체안에 내용을 건들때는 항상new를 통해 생성을 해주어야한다는 것을

자꾸 까먹게 되니 계속 생각을 해야하는것 같다!

 

 

'알고리즘 with 자바 > 자료구조' 카테고리의 다른 글

클래스 ,객체, 참조변수 5  (0) 2021.06.23
클래스, 객체, 참조변수 4  (0) 2021.06.22
클래스, 객체, 참조변수 2  (0) 2021.06.21
클래스 , 객체, 참조변수 1  (0) 2021.06.21
문자열 다루기 2  (0) 2021.06.19

클래스와 객체


int[] numbers = new int[8];

 

정수형 배열 numbers 선언!

 

int는 프리미티브 타입이다..

int형 배열은??? 프리미티브 타입이 아니다!

즉 참조변수이다! 다른 어떤 객체의 주소를 저장하는 변수!!

 

각각의 칸은 정수형 변수이다! 즉 프리미티브 타입의 변수이다.


Person1[] members = new Person1[8]

 

Person1 타입의 배열 members 선언!

배열의 각각 칸 까지도 프리미티브 타입이 아님!

 


package section1;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class code02 {
	
	static Person1 members[]= new Person1[100];
	static int n = 0;

	public static void main(String[] args) {
		try {
			Scanner in = new Scanner(new File("data.txt"));
			while(in.hasNext()) {
				String name = in.next();
				String number = in.next();
				
				members[n] = new Person1();
				members[n].name=name;
				members[n].number=number;
				n++;
			}
			
			
			in.close();
		} catch (FileNotFoundException e) {
			System.out.println("No file");
		}
		
		for(int i=0; i<n; i++) {
			System.out.println(members[i].name + " "+ members[i].number);
		}
	}

}

객체배열 예제! 반복문 내에서 객체배열은 각각의 변수들이 프리미티브 타입이 아니기때문에 

new 연산자가 필요하다!

 

 

 

 

 

 

 

'알고리즘 with 자바 > 자료구조' 카테고리의 다른 글

클래스, 객체, 참조변수 4  (0) 2021.06.22
클래스, 객체, 참조변수 3  (0) 2021.06.22
클래스 , 객체, 참조변수 1  (0) 2021.06.21
문자열 다루기 2  (0) 2021.06.19
문자열 다루기  (0) 2021.06.19

서로 관련있는 데이터들을 하나의 단위로 묶어두면 편할 것이다! 라는 생각에

클래스라는 개념이 등장하는 가장 기본적인 이유이다.

 

클래스는 하나의 타입이다.

(사용자 정의 타입) 

 

package section1;

public class Person1 {
	
	public String name;  //field, data memeber
	public String number;
}

Person1 클래스 생성

 

package section1;

public class code01 {

	public static void main(String[] args) {

		Person1 first = new Person1();  //object
		
		first.name="John";
		first.number="01012345678";
		System.out.println("Name : " + first.name + "," + "Number : " + first.number);
		
		Person1[] members= new Person1[10];
		members[0] = first;
		members[1] = new Person1();
		members[1].name = "David";
		members[1].number = "01098765432";
		
		System.out.println("Name : " + members[1].name + "," + "Number : " + members[1].number);

		
	}

}

Person1타입 으로 first변수를 만들고 

직접 데이터를 넣어주어서 확인해보고

 

Person1타입 배열 members를 만들고

데이터를 넣어줬다!

 

first 라는 변수에는 new로 만든 객체의 주소가 저장이된다

 

Person1 first; 

   - 아직 객체는 생성되지 않고 변수 first만 만들어진다 이때 변수의 값은 null이다

 

first = new Person();

   - new Person1() 명령에 의해 객체가 만들어지고 first에 그 주소를 저장한다.(참조하게됨)

 

first.name = "John"; first.number = "01023456";

   -first가 참조하고 있는 Person1 타입의 객체의 name, number라는 이름의 필드에 데이터를 저장한다.

 

모든 프리미티브 타입의 변수는 보통 변수이다.

즉 변수 자체에 값이 저장된다.

 

프리미티브 타입이 아닌 모든 변수는 참조변수이다.

즉 실제 데이터가 저장될 "객체"는 new명령으로 따로 만들어야 하고, 참조변수에는 그 객체의 주소를 저장한다.

 

 

 

 

 

 

 

 

 

 

 

 

 

+ Recent posts