부산IT JAVA 4

서현우·2022년 3월 24일
0

부산IT 자바

목록 보기
7/11

배열에 객체 저장, 합계, 출력

Person.java

package com.day04;

public class Person {
private String name, department;
private int age;

public Person(String name, int age, String department) {
	this.name=name;
	this.age=age;
	this.department=department;
}


//getter
public String getName() {
	return name;
}

public String getDepartment() {
	return department;
}

public int getAge() {
	return age;
}
}

PersonMain.java

package com.day04;

package com.day04.book07;

public class PersonMain {
	Person[] arr = new Person[10];
	int cnt;
	
	
	public void insertPerson(String name, int age, String dept){
		arr[cnt]=new Person(name,age,dept);
		cnt++;
		
	}
	public void print() {
		int sum=0;
//1번방법. arr[i]==null이면 break;
//		for(int i=0;i<arr.length;i++) {
//			if(arr[i]==null) break;
//			System.out.println(arr[i].getName());
//			System.out.println(arr[i].getAge());
//			sum+=arr[i].getAge();
//		}
//2번방법. cnt만큼 돌리겠다.
		for(int i=0;i<cnt;i++) {
			System.out.println(arr[i].getName());
			System.out.println(arr[i].getAge());
			sum+=arr[i].getAge();
		}
		System.out.println("나이총합:"+sum);
		System.out.println("나이평균:"+sum/(float)cnt);
	}
	
	public static void main(String[] args) {
		PersonMain pm = new PersonMain();
		pm.insertPerson("홍길동",30,"영업부");
		pm.insertPerson("이순신",25,"인사부");
		pm.insertPerson("강감찬",27,"개발부");
		pm.print();
	}
}

배열로 성적 입력, 출력, 순위구하기(객체배열X)

TwoArrayScore.java

package com.day04;

import java.util.Scanner;

public class TwoArrayScore {
	//학번, 국어, 영어, 수학, 총점, 평균, 석차[7] ==> [50][7]
	int[][] arr = new int [50][7];
	static Scanner sc = new Scanner(System.in);
	int row;
	
	public void showMenu() {
		System.out.println("선택하세요>>");
		System.out.println("1.입력 2.전체보기/종료");
		System.out.println("선택>>");
	}
	
	public void inputData() { //성적입력
		System.out.println("학생 성적 입력>>");
		System.out.println("학번>>");
		int stNum = sc.nextInt();
		System.out.println("국어 영어 수학>>");
		int kor = sc.nextInt();
		int eng = sc.nextInt();
		int math = sc.nextInt();
		arr[row][0] = stNum;
		arr[row][1] = kor;
		arr[row][2] = eng;
		arr[row][3] = math;
		arr[row][4] = kor+eng+math;
		arr[row][5] = arr[row][4]/3;
		arr[row][6] = 1;
		row++;
	}
	
	public void viewData() {
		rankMethod();
		System.out.println("----성적보기-----");
		System.out.println("학번\t국어\t영어\t수학\t총점\t평균\t석차");
		for(int i=0;i<row;i++) {
			for(int j=0;j<arr[i].length;j++) {
				System.out.print(arr[i][j]+"\t");
			}
			System.out.println();
		}
	}
	
	private void rankMethod() { //석차구하기
		for(int i=0;i<row-1;i++) {
			for(int j=i+1 ;j<row;j++) {
				if(arr[i][4]>arr[j][4]) {
					arr[j][6]++;
				} else {
					arr[i][6]++;
				}
			}
		}
	}
	
	public static void main(String[] args) {
		TwoArrayScore manager = new TwoArrayScore();
		while(true) {
			manager.showMenu();
			int num = sc.nextInt();
			switch(num) {
			case 1: manager.inputData(); break;
			case 2: manager.viewData(); 
			System.exit(0);
			default: System.out.println("입력오류");
			}
			
		}
//		manager.inputData();
//		manager.viewData();	
	}
}

객체배열에 값 저장해서 출력

Student.java, TeacherMain.java 한세트

Student.java

package com.day04;

public class Student {
private String name;
private int kor,eng,math;
private int rank=1;

//생성자
public Student(String name, int kor, int eng, int math) {
	this.name=name;
	this.kor=kor;
	this.eng=eng;
	this.math=math;
}

//getter
public String getName() {
	return name;
}
public int getKor() {
	return kor;
}
public int getEng() {
	return eng;
}
public int getMath() {
	return math;
}
public int getRank() {
	return rank;
}
//총점 메서드
public int getTotal() {
	return kor+eng+math;
}
//석차 rank1 증가
public void setRank() {
	this.rank++;
}
//평균 메서드
public double getAverage() {
	return getTotal()/3.0;
}

}

TeacherMain.java

package com.day04;

import java.util.Scanner;

public class TeacherMain {
	static Scanner sc = new Scanner(System.in);
	//배열이름 arr
    Student[] arr = new Student[50];
	//배열 인덱스 cnt는 0부터 시작
    int cnt;

	public void showMenu() {
		System.out.println("선택하세요>>");
		System.out.println("1.입력 2.전체보기/종료");
		System.out.println("선택>>");
	}
	
	public void inputData() {
		System.out.println("성적입력>>");
		System.out.println("이름>>");
		String name = sc.next();
		System.out.println("국어 영어 수학>>");
		int kor = sc.nextInt();
		int eng = sc.nextInt();
		int math = sc.nextInt();
		//arr 첫번째에 학생 정보 저장
		arr[cnt++] = new Student(name,kor,eng,math);
	}
	
	public void viewData() {
		rankMethod(); //랭크메서드 호출
		for(int i=0;i<arr.length;i++) {
			if(arr[i]==null) break;
			System.out.println("이름:"+arr[i].getName());
			System.out.println("국어:"+arr[i].getKor());
			System.out.println("영어:"+arr[i].getEng());
			System.out.println("수학:"+arr[i].getMath());
			System.out.println("총점:"+arr[i].getTotal());
			System.out.println("평균:"+arr[i].getAverage());
			System.out.println("석차:"+arr[i].getRank());
		}
	}
	
	public void rankMethod() {
		for(int i=0;i<cnt-1;i++) {
			for(int j=i+1;j<cnt;j++) {
				if(arr[i].getTotal()>arr[j].getTotal()) {
					arr[j].setRank();
				}	else if(arr[i].getTotal()<arr[j].getTotal()){
					arr[i].setRank();
				}
			}
		}
	}
	
	public static void main(String[] args) {	
		
		
		TeacherMain t = new TeacherMain();
		while(true) {
			t.showMenu();
			int num = sc.nextInt();
			switch(num) {
			case 1: t.inputData(); break;
			case 2: t.viewData();  
			System.exit(0);
			default: System.out.println("입력오류");
			}
	}

}
}

static의미 - 게시판 글 번호

package com.day04;

public class BBS {
	private String name, date, title, content;
	//static은 객체마다가 아닌 공통적인(객체끼리 공유하는) 내용
	static private int no;
	
	public BBS(String name, String date, String title, String content) {	
		this.name=name;
		this.date=date;
		this.title=title;
		this.content=content;
	}
	public void print() {
		//static변수는 클래스.변수이름 꼴로 작성
		System.out.println("글번호:"+ ++BBS.no);
		System.out.println("이름:"+name);
		System.out.println("작성일:"+date);
		System.out.println("제목:"+title);
		System.out.println("내용:"+content);
		System.out.println();
	}
	
	
	public static void main(String[] args) {
		BBS b1 = new BBS("홍길동","2021","제목1","내용1");
		BBS b2 = new BBS("홍길동2","2022","제목2","내용2");
		BBS b3 = new BBS("홍길동3","2020","제목3","내용3");
		b1.print();
		b2.print();
		b3.print();
	}
}

객체 배열 예제

PhoneMain.java

package com.day04;

import java.util.Scanner;

class Phone {
	private String name;
	private String tel;
	
	//생성자
	Phone(String name, String tel){
		this.name=name;
		this.tel=tel;
	}
	
	//getter
	public String getName() {
		return name;
	}
	public String getTel() {
		return tel;
	}
}

public class PhoneMain {
	Scanner sc = new Scanner(System.in);
	//배열이름 arr
	int num;
	//arr이 있다고 선언만 하고, 배열길이는 아래 입력받음.
	private Phone[] arr;
	
	public void insertPhone() {
		System.out.println("입력 수>>");
		int num = sc.nextInt();
		//폰형 배열 arr 생성. 
		//배열길이를 지금 입력받으므로 선언과 생성을 나눠서 해야함.
		arr = new Phone[num];
		
		//입력받은 num만큼 반복
		for(int i=0;i<num;i++) {
			System.out.println("이름>>");
			String name = sc.next();
			System.out.println("전화번호>>");
			String tel = sc.next();
			arr[i]=new Phone(name,tel);
		}	
	}
	
	public void viewPhone() {
		for(int i=0;i<arr.length;i++) {
			System.out.println("이름 : "+arr[i].getName());
			System.out.println("전화번호 : "+arr[i].getTel());
			System.out.println();
		}
	}
	
	public static void main(String[] args) {
		PhoneMain pm = new PhoneMain();
		pm.insertPhone(); //입력
		pm.viewPhone(); //전체보기
	}
}

(알고리즘)입력한 금액을 50000,10000,1000,500,100,1원으로 나눴을 때 각 몇 개 씩 있는지 출력

public class ChangeMoney {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("금액을 입력하시오");
		int don = sc.nextInt();//65321입력한다면
		/*
		 * 50000 원 : 1
		 * 10000 원 : 1
		 * 1000 원 : 
		 * 500 원 :
		 * 100 원 :
		 * 1원 : 
		 */
		
        //배열로 만들어서 반복문으로 처리한다.
		int[] unit = {50000,10000,1000,500,100,1};
		
        for(int i=0;i<unit.length;i++) {
			if(don/unit[i]>0)
			System.out.println(unit[i]+"원:"+don/unit[i]);
			don = don%unit[i];
		}	
	}
}
profile
안녕하세요!!

0개의 댓글

관련 채용 정보