반지름과 이름을 가진 Circle 클래스를 작성하고, Circle 클래스의 객체를 생성하라. 글리고 객체가 생성된 모습을 그려보라.
public class Circle {
int radius;
String name;
public Circle() {}
public double getArea(){
return 3.14*radius*radius;
}
public static void main(String[] args) {
Circle pizza = new Circle();
pizza.radius = 10;
pizza.name = "자바피자";
double area = pizza.getArea();
System.out.println(pizza.name+"의 면적은 "+area);
Circle donut = new Circle();
donut.radius = 2;
donut.name = "자바도넛";
area = donut.getArea();
System.out.println(donut.name+"의 면적은 "+area);
}
}
자바피자의 면적은 314.0
자바도넛의 면적은 12.56
너비와 높이를 입력받아 사각형의 합을 출력하는 프로그램을 작성하라. 너비(width)와 높이(height) 필드, 그리고 면적 값을 제공하는 getArea() 메소드를 가진 Rectangle 클래스를 만들어 활용하라.
import java.util.Scanner;
class Rectangle {
int width, height;
public int getArea() {
return width*height;
}
}
public class RectApp {
public static void main(String[] args) {
Rectangle rect = new Rectangle();
Scanner sc = new Scanner(System.in);
System.out.print(">> ");
rect.width = sc.nextInt();
rect.height = sc.nextInt();
System.out.println("사각형의 면적은 "+rect.getArea());
sc.close();
}
}
>> 3 5
사각형의 면적은 15
다음 코드는 2개의 생성자를 가진 Circle 클래스이다. 실행 결과는 무엇인가?
public class Circle {
int radius;
String name;
public Circle() {
radius=1;
name="";
}
public Circle(int r, String n) {
radius = r;
name = n;
}
public double getArea(){
return 3.14*radius*radius;
}
public static void main(String[] args) {
Circle pizza = new Circle(10, "자바피자");
double area = pizza.getArea();
System.out.println(pizza.name+"의 면적은 "+area);
Circle donut = new Circle();
donut.radius = 2;
donut.name = "자바도넛";
area = donut.getArea();
System.out.println(donut.name+"의 면적은 "+area);
}
}
자바피자의 면적은 314.0
자바도넛의 면적은 12.56
제목과 저자를 나타내는 title과 author 필드를 가진 Book 클래스를 작성하고, 생성자를 작성하여 필드를 초기화하라.
public class Book {
String title, author;
public Book(String t) {
title = t;
author = "작자미상";
}
public Book(String t, String a) {
title = t;
author = a;
}
public static void main(String[] args) {
Book littlePrince = new Book("어린왕자", "생텍쥐페리");
System.out.println(littlePrince.title+" "+littlePrince.author);
Book loveStory = new Book("춘향전");
System.out.println(loveStory.title+" "+loveStory.author);
}
}
어린왕자 생텍쥐페리
춘향전 작자미상
예제 4-4에서 작성한 Book 클래스의 생성자를 this()를 이용하여 수정하라.
public class Book {
String title, author;
void show() {
System.out.println(title+" "+author);
}
public Book() {
this("","");
System.out.println("생성자 호출됨");
}
public Book(String title) {
this(title, "작자미상");
}
public Book(String title, String author) {
this.title=title;
this.author=author;
}
public static void main(String[] args) {
Book littlePrince = new Book2("어린왕자", "생텍쥐페리");
Book loveStory = new Book2("춘향전");
Book emptyBook = new Book2();
loveStory.show();
}
}
생성자 호출됨
춘향전 작자미상
반지름이 0~4인 Circle 객체 5개를 가지는 배열을 생성하고, 배열에 있는 모든 Circle 객체의 면적을 출력하라.
class Circle {
int radius;
public Circle(int radius) {
this.radius = radius;
}
public double getArea() {
return 3.14*radius*radius;
}
}
public class CircleArray {
public static void main(String[] args) {
Circle c[] = new Circle[5];
for(int i=0; i<c.length; i++) {
c[i] = new Circle(i);
}
for(int i=0; i<c.length; i++) {
System.out.print((int)(c[i].getArea())+" ");
}
}
}
0 3 12 28 50
예제 4-4의 Book 클래스를 활용하여 2개짜리 Book 객체 배열을 만들고, 사용자로부터 책의 제목과 저자를 입력받아 배열을 완성하라.
import java.util.Scanner;
class Book {
String title, author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
}
public class BookArray {
public static void main(String[] args) {
Book book[] = new Book[2];
Scanner sc = new Scanner(System.in);
for(int i=0; i<book.length; i++) {
System.out.print("제목>>");
String title = sc.nextLine();
System.out.print("저자>>");
String author = sc.nextLine();
book[i] = new Book(title, author);
}
for(int i=0; i< book.length; i++) {
System.out.print("("+book[i].title+", "+book[i].author+")");
}
sc.close();
}
}
제목>>사랑의 기술
저자>>에리히 프롬
제목>>시간의 역사
저자>>스티븐 호킹
(사랑의 기술, 에리히 프롬)(시간의 역사, 스티븐 호킹)
char() 배열을 전달받아 출력하는 printCharArray() 메소드와 배열 속의 공백(' ') 문자를 ','로 대치하는 replaceSpacee() 메소드를 작성하라.
public class ArrayPassingEx {
static void replaceSpace(char a[]) {
for(int i=0; i<a.length; i++){
if(a[i] == ' ') a[i] = ',';
}
}
static void printCharArray(char a[]) {
for(int i=0; i<a.length; i++) {
System.out.print(a[i]);
}
System.out.println();
}
public static void main(String[] args) {
char c[] = {'T','H','I','S',' ','I','S',' ','A',' ','P','E','N','C','I','L'};
printCharArray(c);
replaceSpace(c);
printCharArray(c);
}
}
THIS IS A PENCIL
THIS,IS,A,PENCIL
다음 코드에서 언제 가비지가 발생하는지 설명하라.
public class GarbageEx {
public static void main(String[] args) {
String a = new String("Good");
String b = new String("Bad");
String c = new String("Normal");
String d, e;
a=null;
b=c;
c=null;
}
}
전체 코드를 실행한 후 어떤 레퍼런스도 가리키고 있지 않는 객체나 배열이 가비지가 된다.
다음 코드의 두 클래스 Sample과 AccessEx 클래스는 동일한 패키지에 저장된다. 컴파일 오류를 찾아내고 이유를 설명하라.
class Sample {
public int a;
private int b;
int c; //디폴트 접근 지정
}
public class AccessEx {
public static void main(String[] args) {
Sample sample = new Sample();
sample.a = 10;
sample.b = 10;
sample.c = 10;
}
}
java: b has private access in p4.Sample
Sample 클래스의 필드 b는 private 멤버로서 Sample 클래스 외 다른 어떤 클래스에서도 읽고 쓸 수 없기 때문에 컴파일 오류가 발생한다.
전역 함수로 작성하고자 하는 abs, max, min의 3개 함수를 static 메소드로 작성하고 호출하는 사례를 보여라.
class Calc {
public static int abs(int a) {
return a>0?a:-a;
}
public static int max(int a, int b) {
return (a>b)?a:b;
}
public static int min(int a, int b) {
return (a>b)?b:a;
}
}
public class CalcEx {
public static void main(String[] args) {
System.out.println(Calc.abs(-5));
System.out.println(Calc.max(10,8));
System.out.println(Calc.min(-3,-8));
}
}
5
10
-8
static 멤버를 이용하여 달러와 원화를 변환해주는 환율 계산기를 만들어보자.
import java.util.Scanner;
class CurrencyConverter {
private static double rate;
public static double toDollar(double won) {
return won/rate;
}
public static double toKWR(double dollar) {
return dollar*rate;
}
public static void setRate(double r) {
rate = r; //환율 설정
}
}
public class StaticMember {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("환율(1달러)>>");
double rate = sc.nextDouble();
CurrencyConverter.setRate(rate);
System.out.println("백만원은 $"+CurrencyConverter.toDollar(1000000)+"입니다.");
System.out.println("$100는 "+CurrencyConverter.toKWR(100)+"입니다.");
}
}
환율(1달러)>>1310
백만원은 $763.3587786259542입니다.
$100는 131000.0입니다.