Java/실습

JAVA-클래스 실습(01)

zs1397 2022. 4. 15. 10:58

문제1. 사각형을 나타내는 클래스 Rectangle을 만들어보자. 사각형은 가로(w)와 세로(h)를 가지며, 사각형의 넓이를 반 환하는 area(), 사각형의 둘레를 반환하는 perimeter() 메소드, 객체를 초기화하는 생성자도 함께 선언한다. Rectangle 클래스를 작성하고 객체를 생성하여 테스트하라. 생성자를 사용하여 객체를 초기화 한 후 임의의 값으 로 필드값을 변경한 후 결과도 확인하시오

import java.util.Scanner;

class Rectangle{
	int area(int w,int h) {
		return w*h;
	}
	int perimeter(int w,int h) {
		return (w+h)*2;
	}
}

public class RectangleTest {

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		Rectangle rect = new Rectangle();
		int width, height;
		System.out.print("가로 입력 : ");
		width = input.nextInt();
		System.out.print("세로 입력 : ");
		height = input.nextInt();
		System.out.println ("사각형의 넓이 : " + rect.area(width, height));
		System.out.println ("사각형의 둘레 : " + rect.perimeter(width , height));
	}

}

 

문제2.  날짜를 나타내는 클래스 Date를 만들어보자. Date는 연도, 월, 일 등의 속성을 가지며, 날짜를 “2012.7.12”과 같 이 출력하는 메소드 print1(), 날짜를 “July 12, 2012”와 같이 출력하는 print2() 등의 메소드를 가진다. Date 클래스 를 작성하고 객체를 생성하여서 테스트하라. 

class Date{
	int year, month, date;
	Date(int year, int month, int date){
		this.year=year;
		this.month=month;
		this.date=date;
	}
	void print1() {
		System.out.println(year+"."+month+"."+date);
	}
	void print2() {
		String[] strMonth = {"January","Faburary","March","Aprill","May","June","July",
				"August","September","October","November","December"};
		System.out.println(strMonth[month-1]+""+date+"."+year);
		}
}


public class DateTest {
	public static void main(String[] args) {
		Date date = new Date(2021,8,30);
		date.print1();
		date.print2();
	}

}

문제 3. Circle 객체의 필드 값을 초기화 한 후 넓이를 계산하여 출력하는 프로그램을 완성하시오. 단, 크기가 5인 객 체 배열을 생성하여 처리하고, 입력 받은 값을 생성자 매개변수로 전달하여 필드를 초기화 할수 있도록 하 시오

class Circle{
	private double radius;
	public Circle(double radius) {
		this.radius=radius;
		System.out.printf("radius = %2f\n",radius);
	}
	public double getArea() {
		return 3.14 * radius * radius;
	}
}

public class CircleTest {
	public static void main(String[] args) {
		Circle[] c; //객체배열 선언
		c = new Circle[5]; //배열 생성
		for(int i=0; i<c.length; i++) {
			c[i] = new Circle(Math.random()*10); 
		}
		for(int i=0; i<c.length; i++) {
			System.out.printf("%d] Area: %.2f\n",i+1,c[i].getArea());
		}
	}

}

 

문제 3.

class Shoes{
	private int size, cnt;
	private String type;
	
	Shoes(){
		this(0,0,null);
	}
	Shoes(int size, int cnt, String type){
		this.size=size;
		this.cnt=cnt;
		this.type=type;
	}
	int getSize() {
		return size;
	}
	int getCnt() {
		return cnt;
	}
	String getType() {
		return type;
	}
	void sell(int cnt) {
		this.cnt -= cnt;
	}
	public void add(int cnt) {
		if(cnt<= 0) return;
		this.cnt += cnt; 
	}
	@Override
	public String toString() {
		return "Shoes [size=" + size + ", cnt=" + cnt + ", type=" + type + "]";
	}	
}

public class ShoesTest {

	public static void main(String[] args) {
		Shoes sh=new Shoes(255, 3, "샌들" );
		Shoes sh1=new Shoes(245, 10, "운동화" );
		System.out.println(sh.toString());
		System.out.println("샌들 한 개를 팔았습니다");
		sh.sell(1);
		System.out.println("현재 샌들의 개수는 " + sh.getCnt() + " 입니다");
		System.out.println("샌들 2개를 추가합니다");
		sh.add(2);
		System.out.println("현재 샌들의 개수는 " + sh.getCnt() + " 입니다");
	}

}

문제 4.  영화 Movie 클래스를 정의하여 보자. Movie 클래스는 영화 제목, 평점, 감독, 발표된 연도 등의 필드를 가진 다. 영화의 모든 정보를 화면에 출력하는 print()라는 메소드를 구현하라. Movie 클래스를 작성하고 객체를 생성하여서 테스트하라. 

class Movie{
	String title, direct;
	int value, year;
	
	Movie(String title, String direct, int value, int year){
		this.direct=direct;
		this.title=title;
		this.value=value;
		this.year=year;
	}
	public void print() {
		String result="Movie[title= "+title+",director= "+direct+",value= "+value+",year= "+year+"]";
		System.out.println(result);
	}
}

public class MovieTest {
	public static void main(String[] args) {
		Movie movie = new Movie("한림","소프트웨어",10,2022);
		movie.print();
	}
}

문제 5.  아이디는 키보드로 입력 받으며, 비밀번호는 4자리수의 정수형 난수로 초기화하는 Info 클래스를 제시된 조건대로 작성하시오.

 필드 구성 - id : String, 아이디 저장 - pass : int, 비밀번호 저장

 생성자 : 아이디 필드는 매개변수로 받은 값으로 초기화하고, 난수를 생성하여 비밀번호를 초기화

 disPlay() 메소드 : 아이디와 비밀번호 출력, 반환값 없음 Info 객체를 생성하고 테스트하는 InfoTest 클래스를 작성 하시오.

 main() 메소드 - Info 객체를 두개를 선언하고 아이디는 입력 받아서 생성자 매개변수로 전달 - 두 개의 객체 내용 출력(disPlay()메소드 호출)

import java.util.*;

class Info{
	String id;
	int pass;
	
	Info(String id){
		this.id=id;
		pass=(int)(Math.random()*9000)+1000;
	}
	void disPlay() {
		System.out.println("id: "+id+"\t password: "+pass);
	}
}
public class InfoTest {
	public static void main(String[] args) {
		Scanner key = new Scanner(System.in);
		System.out.print("아이디를 입력하세요 >>>>");
		Info obj1 = new Info(key.next());
		
		System.out.println("첫번째 객체 생성 완료");
		System.out.println("아이디를 입력하세요 >>>>");
		Info obj2 = new Info(key.next());
		System.out.println("두번째 객체 생성 완료");
		System.out.println("\n 첫번째 객체의 아이디와 비밀번호 출력");
		obj1.disPlay();
		System.out.println("\n 두번째 객체의 아이디와 비밀번호 출력");
		obj2.disPlay();
	}
	
}

문제 6.  다음의 내용을 클래스(CellPhone)로 작성하시오. - 핸드폰에는 폰 번호와 현재 전원의 상태를 저장하고 있다.

- 폰이 처음 생성될 때는 폰 번호를 저장하고, 현재의 전원 상태를 on상태(true)로 한다.

- 기능으로는 전원 버튼을 누를 때 마다 현재의 전원 상태를 토글(on(true)/off(false)) 한다.

- 현재 객체 상태를 문자열로 리턴한다.

- telNum, power, toString(), powerToggle()

class CellPhone{
	private String telNum;
	private boolean power;
	
	CellPhone(){
		this("000-000-0000");
	}
	CellPhone(String tn){
		this.telNum=tn;
		this.power=true;
	}
	void powerToggle() {
		this.power=!this.power;
	}
	@Override
	public String toString() {
		return " [폰번호=" + telNum + ", 전원상태=" + power + "]";
	}
}

public class CellPhoneTest {
	public static void main(String[] args) {
		CellPhone p1 = new CellPhone();
		System.out.println(p1);
		
		p1.powerToggle();
		System.out.println(p1);
		
		CellPhone p2 = new CellPhone("111-111-1111");
		System.out.println(p2);
		p2.powerToggle();
		System.out.println(p2);
	}
}

'Java > 실습' 카테고리의 다른 글

JAVA-상속 실습(다형성, 추상, 강제 형 변환)  (0) 2022.04.20
JAVA - 클래스와 상속 실습  (0) 2022.04.19
JAVA- 클래스 실습(02)  (0) 2022.04.15