1. Constructor
- 클래스와 동일한 이름이어야 한다
- 파라미터 개수와 타입이 다르면 이름을 중복해서 사용할 수 있다.
- 특별한 메소드
- 반환 데이터형이 없다
import java.util.Scanner; public class test1 { public static void main(String[] args) { System.out.println("====생성자 Calu의 a===="); Calu a = new Calu(); // cnt + 1 a.Input(); a.Print(); System.out.println("====생성자 Calu의 b===="); Calu b = new Calu("포테이토칩"); b.Print(); System.out.println("====생성자 Calu의 c===="); Calu c = new Calu(2); c.Print(); System.out.println("====생성자 Calu의 d===="); Calu d = new Calu("고구마칩",5); d.Print(); } } class Calu{ String producName; int cnt=0; public Calu() { cnt++; } public Calu(String name) { this.producName = name; } public Calu(int cnt) { this.cnt = cnt; } public Calu(String name, int cnt) { this.producName = name; this.cnt = cnt; } public void Input() { Scanner scan = new Scanner(System.in); System.out.println("상품이름 : "); this.producName = scan.next(); System.out.println("개수 : "); this.cnt = scan.nextInt(); } public void Print() { System.out.println( "상품명 : "+this.producName +"\n개수 : "+this.cnt ); } }
2. 배열
여러 데이터를 묶어서 사용하기 위함
import java.util.Scanner; public class test1 { public static void main(String[] args) { String[] name = new String[] {"홍길일","홍길이","홍길삼","홍길사","홍길오"}; int[] kor = new int[] {95,87,68,79,91}; int[] eng = new int[] {80,95,88,71,97}; int[] mat = new int[] {61,58,97,99,68}; StudData[] std = new StudData[name.length]; for(int i=0;i<std.length;i++) std[i]= new StudData(name[i],kor[i],eng[i],mat[i]); StudData.StudPrintHead(); for(int i =0;i<std.length;i++) std[i].StudPrint(); Calu c = new Calu(); int korTotal = c.sums(kor); int engTotal = c.sums(eng); int matTotal = c.sums(mat); System.out.println("============================================"); System.out.println("총합\t"+korTotal+"\t"+engTotal+"\t"+matTotal); double korAvg = c.average(kor); double engAvg = c.average(eng); double matAvg = c.average(mat); System.out.println("평균\t"+korAvg+"\t"+engAvg+"\t"+matAvg); } } class StudData{ private String name; private int kor; private int eng; private int mat; private int total_sum; private double total_avg; private Calu c; public StudData() { } public StudData(String name,int kor, int eng, int mat) { this.name = name; this.kor = kor; this.eng = eng; this.mat = mat; } public void StudPrint() { System.out.println( name+"\t"+kor+"\t"+eng+"\t"+mat+"\t"+StdSum()+"\t"+StdAvg() ); } public static void StudPrintHead() { System.out.println("이름\t국어\t영어\t수학\t합계\t평균"); } public int StdSum() { return kor+eng+mat; } public double StdAvg(){ return (kor+eng+mat)/3; } } class Calu{ public int sums(int[] temp) { int result = 0; for(int i=0;i<temp.length;i++) { result = result + temp[i]; } return result; } public double average(int[] temp) { double result = 0; for(int i=0;i<temp.length;i++) { result = result + temp[i]; } return result/temp.length; } }