명품자바프로그래밍 Chapter4_Lab03
실습2 | Grade 클래스 작성
import java.util.Scanner;
public class Grade {
private int math; //멤버 변수 선언
private int science;
private int english;
public Grade(int m,int s, int e) { //생성자 메소드 작성
this.math = m; // 매개변수 받아 멤버 변수에 저장
this.science = s;
this.english = e;
}
public int average() { //세과목의 평균을 리턴하는 average() 메소드 작성
return (math + science + english) /3;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("수학, 과학, 영어 순으로 3개의 점수 입력>>");
int math = scanner.nextInt();
int science = scanner.nextInt();
int english = scanner.nextInt();
Grade me = new Grade(math,science,english);
System.out.println("평균은 "+me.average()); //average()는 평균을 계산하여 리턴
scanner.close();
}
}
실습4 직사각형 클래스 작성
public class Rectangle {
int x,y,width,height; //사각형을 구성하는 점과 크기 정보
//x,y,width,height 값을 매개 변수로 받아 필드를 초기화하는 생성자
public Rectangle(int x,int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
//int square() : 사각형 넓이 리턴
public int square() {
return (this.width * this.height);
}
//void show(): 사각형의 좌표와 넓이를 화면에 출력
public void show() {
System.out.printf("(%d,%d)에서 크기가 %dX%d인 사각형\n",this.x,this.y,this.width,this.height);
}
//boolean contains(Rectangle r): 매개변수로 받은 r이 현 사각형 안에 있으면 true 리턴
//사각형이 동일하면 true 리턴
//x축은 오른쪽으로 증가, y축은 아래로 증가
public boolean contains(Rectangle r) { //r이랑 s 매개변수로 받고 t랑 비교
if ((this.x <= r.x)&&(this.y<=r.y)&&(this.x + this.width)>=(r.x + r.width) && (this.y + this.height)>= (r.y + r.height))
return true;
else
return false;
}
public static void main(String[] args) {
Rectangle r = new Rectangle(2,2,8,7);
Rectangle s = new Rectangle(5,5,6,6);
Rectangle t = new Rectangle(1,1,10,10);
r.show();
System.out.println("s의 면적은 "+ s.square());
if (t.contains(r))
System.out.println("t는 r을 포함합니다.");
if (t.contains(s))
System.out.println("t는 s를 포함합니다.");
}
}
실습5,6| Circle 클래스와 CircleManager 클래스를 완성하라
import java.util.Scanner;
class Circle{
private double x,y;
private int radius;
public Circle(double x, double y, int radius) {
this.x = x; //x 초기화
this.y = y; //y 초기화
this.radius = radius; //radius 초기화
}
public void show() { // 화면에 출력
System.out.printf("(%.1f,%.1f)%d\n",this.x,this.y,this.radius);
}
public double getArea() { //PI값은 Math 클래스의 PI상수 활용. Math.PI
return (Math.PI * this.radius * this.radius); //면적 계산하여 반환;
}
}
public class CircleManager {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Circle c [] = new Circle[3]; //3개의 객체 배열 선언
for(int i=0;i<c.length;i++) { //c의 길이만큼 반복문 실행
System.out.print("x,y,radius >> ");
double x = scanner.nextDouble(); //x값 읽기
double y = scanner.nextDouble(); //y값 읽기
int radius = scanner.nextInt(); //radius 읽기
c[i] = new Circle(x,y,radius); //Circle 객체 생성
}
for (int i =0;i<c.length;i++)
c[i].show(); //모든 Circle 객체 출력( 해당 메소드 출력)
int biggestIndex = 0;
for (int i = 1;i<c.length ; i++) {
if (c[biggestIndex].getArea() < c[i].getArea()) //면적 함수를 통해 비교
biggestIndex = i; //가장 큰 면적을 가진 index를 저장;
}
System.out.print("가장 면적이 큰 원은 ");
c[biggestIndex].show();
scanner.close();
}
}
실습8 | PhoneBook 클래스를 작성하라
import java.util.Scanner;
class Phone { //phone 클래스
private String name;
private String tel;
public Phone(String name, String tel) { //생성자
this.name = name; //초기화
this.tel = tel; //초기화
}
public String GetName() { //접근자 메소드
return name;
}
public String GetTel() { //접근자 메소드
return tel;
}
public void show() { //검색할때 맞는 경우 출력하는 메소드
System.out.printf("%s의 번호는 %s 입니다.\n",this.name,this.tel);
}
}
public class PhoneBook { //PhoneBook 클래스
Scanner scan = new Scanner(System.in);
int NumOfPeople;
Phone phone[]; // 객체 배열 선언
String name, tel;
public void Getnum() { //Hint - PhoneBook 클래스에서 만들기
System.out.print("인원수>>");
NumOfPeople = scan.nextInt(); //저장할 사람의 수를 입력
phone = new Phone[NumOfPeople]; //phone 객체 배열 생성(입력받은 수 만큼)
}
public void GetInfo() {
for (int i=0;i<NumOfPeople;i++) { //입력받은 수 만큼 Info 입력
System.out.print("이름과 번호는 빈 칸없이 입력>>");
name = scan.next();
tel = scan.next();
phone[i] = new Phone(name,tel); //한 사람의 정보는 하나의 Phone 객체에 저장
}
System.out.println("저장되었습니다...");
}
public void Search() {
while(true) {
System.out.print("검색할 이름>>");
name = scan.next(); //검색할 이름 입력
if (name.equals("그만")) //while문 탈출 조건
break;
for (int i = 0;i<NumOfPeople;i++) { //입력받은 인원수 만큼 반복문 실행
if (name.equals(phone[i].GetName())) { //입력받은 name과 같은 이름이 있는 지 확인
phone[i].show(); //있다면 출력하고 break
break;
}
if (i == (NumOfPeople-1)) //마지막까지 안나온 경우면 없는 이름
System.out.println(name + "은 없습니다.");
}
}
}
public static void main(String[] args) {
PhoneBook p = new PhoneBook();
p.Getnum(); //7번실습을 참고하여 같은 틀로 진행
p.GetInfo();
p.Search();
}
}
+ 실습과제
* 비행기 Plane 클래스를 설계하라
class Plane{
private String model; //멤버 변수(필드) 선언
private int num; //private 멤버
static int planes =0; // 지금까지 생성된 비행기의 개수를 나타내는 정적변수 planes
//생성자 작성: 2~3개 중복 정의(모든 데이터를 받을 수 있고 또는 하나도 안 받을 수 있음)
public Plane() { //매개변수 없음
this("",0);
}
public Plane(int num) { //매개변수 1개
this("",num);
}
public Plane(String model,int num) { //생성자
this.model = model;
this.num = num;
planes++;
}
//멤버 변수를 접근할 수 있는 접근자 메소드 정의
public String Getmodel() {
return model;
}
public int Getnum() {
return num;
}
// 설정자 메소드 작성
public void Setmodel(String Set_model) {
model = Set_model;
}
public void Setnum(int Set_num) {
num = Set_num;
}
//정적 변수 접근할 수 있는 접근자 메소드 getPlanes() 작성
static int getPlanes() {
return planes;
}
//객체의 정보를 문자열로 반환하는 toString 메소드 작성
public String toString() {
return "Plane [model="+this.model+", seats="+this.num+"]";
}
}
public class PlaneTest {
public static void main(String[] args) {
//Plane 객체 여러개 생성
Plane plane1 = new Plane("보잉 777",200);
Plane plane2 = new Plane(500);
Plane plane3 = new Plane("보잉 737",120);
//접근자 메소드와 설정자 메소드를 호출
plane2.Setmodel("에어버스 - A380"); // plane2의 모델 설정자 메소드 호출
plane2.Getnum(); //접근자 메소드 호출
//전체 보유 비행기 수 출력 (planes 변수명 사용)
System.out.println("전체 보유 비행기 수 = "+ Plane.getPlanes());
//비행기 정보 출력
System.out.println("각 비행기 정보 출력");
System.out.println(plane1.toString());
System.out.println(plane2.toString());
System.out.println(plane3.toString());
}
}
* 주사위 Dice 클래스를 만들어라
class Dice{
private int value;
public Dice() {
value = 0;
}
void roll() {
this.value = (int)(Math.random()*6)+1; //랜덤 변수를 사용하여 1~6사이의 값을 저장
}
int getValue() {
return this.value; //주사위 변의 값을 반환
}
}
public class DiceTest {
public static void main(String[] args) {
Dice d1 = new Dice(); //주사위 2개 객체 생성
Dice d2 = new Dice();
int count=0; //주사위 굴린 횟수를 세는 변수 선언 및 초기화
do {
d1.roll(); //d1의 value 랜덤으로 돌리기, 메소드 호출
d2.roll(); //d2의 value 랜덤으로 돌리기, 메소드 호출
System.out.println("주사위1="+ d1.getValue() +" 주사위2="+ d2.getValue());
count++; //실행횟수 증가
}while(d1.getValue()!= 1 || d2.getValue()!=1); //반복조건 작성 (1,1)일 때 탈출
System.out.println("(1,1)이 나오는 데 걸린 횟수 = "+ count);
}
}
'Programming > JAVA' 카테고리의 다른 글
패키지 개념과 자바 기본 패키지 (0) | 2020.10.16 |
---|---|
상속 (0) | 2020.10.16 |
반복문과 배열 그리고 예외 처리 (0) | 2020.09.08 |
[Java] print, printf, println의 차이 (0) | 2020.09.03 |
자바의 기본 구조 (0) | 2020.09.02 |
댓글