Skip to content
Home » 자바 클래스 문제 | [자바 기초 12] 연습문제: 메소드 89 개의 가장 정확한 답변

자바 클래스 문제 | [자바 기초 12] 연습문제: 메소드 89 개의 가장 정확한 답변

당신은 주제를 찾고 있습니까 “자바 클래스 문제 – [자바 기초 12] 연습문제: 메소드“? 다음 카테고리의 웹사이트 https://kk.taphoamini.com 에서 귀하의 모든 질문에 답변해 드립니다: https://kk.taphoamini.com/wiki/. 바로 아래에서 답을 찾을 수 있습니다. 작성자 홍팍 이(가) 작성한 기사에는 조회수 4,273회 및 좋아요 33개 개의 좋아요가 있습니다.

Table of Contents

자바 클래스 문제 주제에 대한 동영상 보기

여기에서 이 주제에 대한 비디오를 시청하십시오. 주의 깊게 살펴보고 읽고 있는 내용에 대한 피드백을 제공하세요!

d여기에서 [자바 기초 12] 연습문제: 메소드 – 자바 클래스 문제 주제에 대한 세부정보를 참조하세요

메소드관련 연습문제를 풀어봅시다.
도서구매: http://www.yes24.com/Product/Goods/104740689
강의자료: https://cloudstudying.kr/courses/10
실습문제: https://cloudstudying.kr/lectures/81#tab
강의문의: [email protected]
카톡ID: chaesam

자바 클래스 문제 주제에 대한 자세한 내용은 여기를 참조하세요.

JAVA (자바) – 클래스 연습 문제 모음 – (1) – 개발이 하고 싶어요

JAVA (자바) – 클래스 연습 문제 모음 – (1) 문제 1 – 다음을 만족하는 Student 클래스를 작성하시오. · String형의 학과와 정수형의 학번을 필드로 …

+ 여기에 더 보기

Source: iu-corner.tistory.com

Date Published: 2/16/2022

View: 6367

[22] 클래스를 활용한 연습 문제 – velog

– public Manager 소스 코드 (). package kosta.phone; import java.util.Scanner; public Manager { Scanner sc = new Scanner(System.

+ 여기를 클릭

Source: velog.io

Date Published: 2/17/2022

View: 6535

04장 연습문제 – 점프 투 자바

다음 코드의 출력 결과는 무엇일까? (눈으로 해석하고 풀어보자.) public Sample { public static vo main(String[] args) …

+ 더 읽기

Source: wikidocs.net

Date Published: 9/10/2021

View: 9827

Java 기초 클래스 – 연습문제(2) – 자유롭게 사는 – 티스토리

기본 환경 JDK : 1.8.0_261 버전 JRE : 1.8.0_261 버전 JAVA VERSION : 8 업데이트 261 Eclipse IDE VERSION : 2020-06버전 시나리오 Triangle …

+ 여기를 클릭

Source: kkungchan.tistory.com

Date Published: 7/18/2022

View: 122

[명품 JAVA] 4장 실습문제 (클래스와 객체) – 낭람

[공지] 코딩, 솔루션, 포스팅 주제 관련 [4장 1번] 자바 클래스를 작성하는 연습을 해보자. 다음 main() 메소드를 실행하였을 때 예시와 같이 출력 …

+ 여기에 자세히 보기

Source: security-nanglam.tistory.com

Date Published: 4/18/2022

View: 727

JAVA1_day15 | 클래스 Class 연습문제 (1) – UBANGE – 티스토리

문제1. 10을 return해주는 클래스 getNumber() … 문제3. “인스턴스 메서드 입니다.” 라는 출력문을 보여주는 클래스 … import java.util.Scanner;.

+ 여기에 표시

Source: ubange.tistory.com

Date Published: 5/20/2022

View: 6703

<명품 JAVA Programming> – Chapter4 연습문제(1, 2, 3, 4, 5, 6)

1. 자바 클래스를 작성하는 연습을 해보자. 다음 main()메소드를 실행하였을 때 예시와 같이 출력되도록 TV 클래스를 작성하라. package chapter4; …

+ 여기를 클릭

Source: kiffblog.tistory.com

Date Published: 12/4/2022

View: 8709

자바 클래스 문제 | Java – 13. 클래스 134 개의 가장 정확한 답변

JAVA (자바) – 클래스 연습 문제 모음 – (1) 문제 1 – 다음을 만족하는 Student 클래스를 작성하시오. · String형의 학과와 정수형의 학번을 필드로 …

+ 여기에 보기

Source: you.dianhac.com.vn

Date Published: 8/29/2022

View: 6759

[Java] 연습문제 – 붕어의 코딩 공부 기록 – 티스토리

06-3의 <학번 생성하기> 예제를 참고하여 카드가 생성될 때마다 카드 번호가 자동으로 증가할 수 있도록 카드 클래스를 만들고 생성해보자. ​. ​. <내가 ...

+ 자세한 내용은 여기를 클릭하십시오

Source: poew.tistory.com

Date Published: 12/7/2022

View: 9081

Top 30 자바 클래스 문제 The 5 Correct Answer

JAVA (자바) – 클래스 연습 문제 모음 – (1) 문제 1 – 다음을 만족하는 Student 클래스를 작성하시오. · String형의 학과와 정수형의 학번을 필드로 선언 …

+ 여기에 자세히 보기

Source: toplist.future-user.com

Date Published: 2/29/2022

View: 6135

주제와 관련된 이미지 자바 클래스 문제

주제와 관련된 더 많은 사진을 참조하십시오 [자바 기초 12] 연습문제: 메소드. 댓글에서 더 많은 관련 이미지를 보거나 필요한 경우 더 많은 관련 기사를 볼 수 있습니다.

[자바 기초 12] 연습문제: 메소드
[자바 기초 12] 연습문제: 메소드

주제에 대한 기사 평가 자바 클래스 문제

  • Author: 홍팍
  • Views: 조회수 4,273회
  • Likes: 좋아요 33개
  • Date Published: 2018. 4. 25.
  • Video Url link: https://www.youtube.com/watch?v=00Hl7WwYeFY

JAVA (자바) – 클래스 연습 문제 모음 – (1)

반응형

JAVA (자바) – 클래스 연습 문제 모음 – (1)

문제 1 – 다음을 만족하는 Student 클래스를 작성하시오.

· String형의 학과와 정수형의 학번을 필드로 선언

· Student 클래스의 main() 메소드에서 Student 객체를 생성하여 학과와 학번 필드에 적당한 값을 입력 후 출력

문제 – 2. 위에서 구현한 Student 클래스를 다음을 만족하도록 기능을 추가하여 작성하시오.

· 필드를 모두 private로 하고, getter와 setter를 구현하고

· Student 클래스의 main() 메소드에서 Student 객체를 생성하여 setter를 사용하여 학과와 학번 필드에 적당한 값을 입력 후 출력

문제 – 3. 다음에 구현된 Circle 클래스를 참고로 다음을 만족하는 Cylinder 클래스를 작성하시오.

· 원통을 나타내는 Cylinder 클래스는 Circle형의 원과 실수형의 높이를 필드로 선언

· 메소드 getVolume()은 원통의 부피를 반환

· Cylinder 클래스의 main() 메소드에서 반지름이 2.8, 높이가 5.6의 원통의 부피를 출력

· 다음은 원을 나타내는 클래스 Circle

public class Circle { public double radius; public static double PI = 3.141592; //생성자 구현 public Circle(double radius) { this.radius = radius; } //현재 반지름을 사용하여 원의 면적을 구하는 메소드 public double getArea() { return radius * radius * PI; } }

문제 4 – 위에서 구현한 Cylinder를 다음 조건에 맞도록 기능을 추가하여 작성하시오.

· 다음과 같은 객체 생성이 가능하도록 생성자를 구현

ㆍ Cylinder cd = new Cylinder(new Circle(2.8), 5.6);

문제 5 – 다음을 만족하는 클래스 SalaryMan을 작성하시오.

· 필드 salary는 월 급여액를 저장하며, int형으로 초기 값으로 1000000 저장

· 메소드 getAnnualGross()는 연봉을 반환하는 메소드로 월급에 보너스 500%로 계산

· 기본 생성자에서 필드 salary의 초기 값을 사용하며, 정수형 인자인 생성자에서 인자가 월 급여액으로 지정

· 다음과 같이 객체를 생성하여 메소드 getAnnualGrass()를 호출하여 출력

System.out.println(new SalaryMan().getAnnualGross());

System.out.println(new SalaryMan(2_000_000).getAnnualGross());

문제 6 – 다음을 만족하는 클래스 Account를 작성하시오.

· 다음의 2 개의 필드를 선언

private String owner;

private long balance;

· 위 모든 필드에 대한 getter와 setter의 구현

· 위 모든 필드를 사용하는 가능한 모든 생성자의 구현

문제 7 – 위에서 구현된 클래스 Account에서 다음 기능을 추가하여 작성하시오.

· 메소드 deposit()의 헤드는 다음과 같으며 인자인 금액을 저축하는 메소드

public long deposit(long amount)

· 메소드 withdraw()의 헤드는 다음과 같으며 인자인 금액을 인출하는 메소드

public long withdraw(long amount)

· Account 클래스의 main() 메소드에서 Account 객체를 생성하여 적당한 저축과 인출을 수행한 후 잔금을 출력

문제 8 – 위에서 구현된 메소드 withdraw()를 다음 조건에 맞게 다시 작성하시오.

· 인출 상한 금액은 잔액까지로 하며, 이 경우 이러한 상황을 출력

· 클래스 AccountTest의 main() 메소드에서 인출 상한 이상의 금액을 인출하려는 메소드를 호출하여 출력

문제 – 9. 다음을 만족하는 클래스 Rectangle을 작성하시오.

· 사각형의 가로와 세로로 객체를 생성하는 생성자

· 면적을 반환하는 메소드 getArea(), 둘레를 반환하는 메소드 getCircumference(),

· 다음과 같이 클래스 Rectangle 이용

Rectangle rc = new Rectangle(3.82, 8.65);

System.out.println(“면적: ” + rc.getArea());

System.out.println(“둘레: ” + rc.getCircumference());

문제 – 10. 다음을 만족하는 클래스 Computer를 작성하시오.

· 다음을 상수 필드로 선언

public … String[] osType = {“원도7”, “애플 OS X”, “안드로이드”};

· 다음과 같은 클래스 Computer의 객체의 사용 결과에 적합하도록 생성자와 메소드 구현

Computer pc = new Computer(0, 16);

Computer apple = new Computer(1, 32);

Computer galaxy = new Computer(2, 16);

pc.print();

apple.print();

galaxy.print();

운영체제: 원도7, 메인메모리: 16 운영체제: 애플 OS X, 메인메모리: 32 운영체제: 안드로이드, 메인메모리: 16

public cla

소스 코드

문제 1 + 2

package ex1; import java.util.Scanner; class StudentEx2{ private String name; private int id; void setName(String name) { // setter 네임 this.name = name; } String getName() { // getter id return this.name+” 학과”; } void setId(int id) { this.id = id; } int getId() { return this.id; } } public class StudentEx1 { public static void main(String[] args) { /* * 다음을 만족하는 Student 클래스를 작성하시오 * String 형의 학과와 정수형의 학번을 필드로 선언 * Student 클래스의 main()메소드에서 Student 객체를 생성하여 학과와 학번 필드에 * 적당한 값을 입력한 후 출력 * 2. 위에서 구현한 Student 클래스를 다음을 만족하도록 기능을 추가하여 작성하시오. 필드를 모두 private로 하고, getter와 setter를 구현하고 Student 클래스의 main() 메소드에서 Student 객체를 생성하여 setter를 사용하여 학과와 학번 필드에 적당한 값을 입력 후 출력 */ Scanner sc = new Scanner(System.in); StudentEx2 student1 = new StudentEx2(); System.out.println(“—회원가입—“); System.out.print(“학과 입력 :”); String name = sc.next(); student1.setName(name); System.out.print(“학번 입력 :”); int id = sc.nextInt(); student1.setId(id); System.out.println(“학생1의 학과 :”+student1.getName()+”, 학번 :”+student1.getId()); } }

문제 3+4

package ex1; public class Circle { public double radius; // 필드(==인스턴스)변수 선언 public static double PI = 3.141592; // 원주율 // 생성자 구현 public Circle(double radius) { this.radius = radius; } // 기능 구현 public double getArea() { return radius * radius * PI; // 원의 면적을 구하는 공식 반지름*반지름*파이 } }

package ex1; public class Cylinder { Circle cir; double height; public Cylinder(Circle cir,double height) { // TODO Auto-generated constructor stub this.cir=cir; this.height=height; } // 생성자 구현 public double Volum() { return cir.getArea()*height; // 반지름과 높이를 곱함.. } public static void main(String[] args) { // 반지름이 2.8 , 높이가 5.6의 원통의 부피를 출력 Circle cp = new Circle(2.8); // 반지름 2.8 Cylinder cd = new Cylinder(new Circle(2.8), 5.6); // Circle 생성자의 2.8, Cylinder 5.6 double height = 5.6; // radius 2.8 height 5.6 // 부피 구하는 법 : 원의 면적 * 높이 . >> 면적은 반지름+반지름+파이 파이먹고싶다 System.out.println(“부피 : “+(cp.getArea()*height)); System.out.println(cd.Volum()); // 동일한 결과 } } /* * 3. 다음에 구현된 Circle 클래스를 참고로 다음을 만족하는 Cylinder 클래스를 작성하시오. · 원통을 나타내는 Cylinder 클래스는 Circle형의 원과 실수형의 높이를 필드로 선언 · 메소드 getVolume()은 원통의 부피를 반환 · Cylinder 클래스의 main() 메소드에서 반지름이 2.8, 높이가 5.6의 원통의 부피를 출력 · 다음은 원을 나타내는 클래스 Circle 4. 위에서 구현한 Cylinder를 다음 조건에 맞도록 기능을 추가하여 작성하시오. · 다음과 같은 객체 생성이 가능하도록 생성자를 구현 ㆍ Cylinder cd = new Cylinder(new Circle(2.8), 5.6); */

문제 5

package Salary; public class SalaryMan { int salary; //월 급여 액 저장 초기값 1,000,000 저장 SalaryMan(){ this.salary = 1000000; } SalaryMan(int salary){ // 생성자에서 인자 월 급여액을 지정하기 위한 재정의 this.salary=salary; } public int getAnnualGross() { // 연봉.. 연봉은 월 * 12 인데 // 보너스 500%를 수령해야 하니까 5.0을 곱해야하지만 int 정수형이므로 5만 곱하고 return (this.salary*12)+(this.salary*5); // 연봉 + 500% 보너스 수령 // 연봉 리턴 } public static void main(String[] args) { SalaryMan user = new SalaryMan(); user.salary = 1500000; // 연봉 1800만 * 보너스 750만 // 최저도 못받는 인생인데 보너스가 쎄네 System.out.println(user.getAnnualGross()); System.out.println(); System.out.println(new SalaryMan().getAnnualGross()); System.out.println(new SalaryMan(2000000).getAnnualGross()); } } /* 5. 다음을 만족하는 클래스 SalaryMan을 작성하시오. · 필드 salary는 월 급여액를 저장하며, int형으로 초기 값으로 1000000 저장 · 메소드 getAnnualGross()는 연봉을 반환하는 메소드로 월급에 보너스 500%로 계산 · 기본 생성자에서 필드 salary의 초기 값을 사용하며, 정수형 인자인 생성자에서 인자가 월 급여액으로 지정 · 다음과 같이 객체를 생성하여 메소드 getAnnualGrass()를 호출하여 출력 System.out.println(new SalaryMan().getAnnualGross()); System.out.println(new SalaryMan(2_000_000).getAnnualGross()); */

문제 6 + 7 + 8

package Account; import java.util.Scanner; class Account { private String owner; private long balance; Account(){ // default 생성자 } Account(String owner){ this.owner = owner; } Account(long balance){ this.balance=balance; } Account(String owner, long balance){ this.owner = owner; this.balance = balance; } void setOwner(String owner) { this.owner = owner; } String getOwner() { return this.owner; } void setBalance(long balance) { this.balance = balance; } long getBalance() { return this.balance; } public long deposit(long amount) { // 인자인 금액을 저축하는 기능 System.out.println(amount+”만큼 입금 합니다.”); return this.balance+=amount; //저장 } public long withdraw(long amount) { // 입력한 금액만큼 인출한 기능 Scanner sc = new Scanner (System.in); long money = amount; // 새로운 money 변수를 선언 System.out.println(“현재 고객님은 “+this.balance+”원 까지 인출할 수 있습니다.”); if(this.balance < amount ) { // 현재 값이 입력 값보다 적다면 System.out.println("잔액이 부족하여 인출하실 수 없습니다."); System.out.println("가진 금액을 모두 출금 하시겠습니까? y/n"); String se[] = {"y","n"}; String sel = sc.next(); if(sel.equals(se[0])) { money = this.balance; // 현재 돈을 money값에 대입 } } System.out.println(money+"만큼 인출 합니다."); return this.balance -= money; // money값 } void show() { System.out.println(this.owner+"님은 현재 "+this.balance+"원을 가지고 있습니다."); } } public class Main { public static void main(String[] args) { Scanner sc = new Scanner (System.in); Account player = new Account(); // 생성자 System.out.print("사용자 성함을 입력하세요 :"); String owner = sc.next(); player.setOwner(owner); System.out.print("사용자의 잔액은 얼만큼 있는지 적으세요. :"); long balance = sc.nextLong(); player.setBalance(balance); player.show(); System.out.println("얼만큼 저축 하시겠습니까?"); int amo = sc.nextInt(); player.deposit(amo); player.show(); System.out.println("얼마를 인출 하시겠습니까?"); amo = sc.nextInt(); player.withdraw(amo); player.show(); } } 9 - package Rectangle; public class Rectangle { double width; double length; Rectangle(double width, double length){ this.width=width; this.length=length; } double getArea() { // 면적 (가로*세로) return this.width * this.length; } double getCircumference() { // 둘레 (가로+높이)*2 return (this.width+this.length)*2 ; } public static void main(String[] args) { // 사각형의 가로와 세로로 객체를 생성하는 생성자 // 면적을 반환하는 메소드 getArea(), // 둘레를 반환하는 메소드 getCircumference(), // 다음과 같이 클래스 Rectangle 이용 // Rectangle rc = new Rectangle(3.82, 8.65); // System.out.println("면적 : "+rc.getArea()); // System.out.println("둘레 : "+rc.getCircumference()); Rectangle rc = new Rectangle(3.82,8.65); System.out.println("가로:3.82, 세로: 8.65"); System.out.println("면적 : "+rc.getArea()); System.out.println("둘레 : "+rc.getCircumference()); } } 10 - package Computer; class Computer{ public static final String[] osType = {"윈도우7","애플 OS X","안드로이드"}; private int OS; // 배열의 인덱스 i 역할을 할 것임 int Memory = 8; Computer(int OS,int Memory){ this.OS = OS; this.Memory = Memory; } void show() { System.out.printf("운영체제: %s, 메인메모리: %d %n", osType[OS], Memory); } } public class Main { public static void main(String[] args) { Computer pc = new Computer(0,16); Computer apple = new Computer(1,32); Computer Android = new Computer(2, 16); pc.show(); apple.show(); Android.show(); } } 반응형

[22] 클래스를 활용한 연습 문제

문제) 전화번호부를 관리하는 프로그램을 만들어보자.

– public class PhoneInfo 소스 코드 (class)

package kosta.phone; public class PhoneInfo { // 전화번호부 관리프로그램 구현하자 (1명의 전화번호부 ) // 상태 : 이름, 전화번호, 생년월일 // 기능 : 1명의 전화내역을 출력 // 1. 각각의 상태에 따른 필드(속성)을 선언한다. String name; // 이름 String phoneNo; // 전화번호 String birth; // 생년월일 // 2. 사용할 생성자를 생성한다. (생성자는 리턴형이 존재하지 않는다.) public PhoneInfo() {} // 디폴트 생성자(기본 생성자) : 입력매개변수(파라미터)가 아무것도 없을 때를 항상 생각한다. // 3. Source 메뉴에서 필드를 통해서 만들어준다. (직접 입력도 가능하다.) public PhoneInfo(String name, String phoneNo, String birth) { super(); this.name = name; this.phoneNo = phoneNo; this.birth = birth; } // 4. 전화내역을 출력할 메서드를 생성한다. public void show() { // 출력은 리턴값이 필요하지 않기 때문에, void를 사용한다. -> void의 사용은 입력매개변수(파라미터)가 없음과도 같다. System.out.println(“이름 : “+name); System.out.println(“전화번호 : “+phoneNo); System.out.println(“생년월일 : “+birth); } // -> 상태와 기능을 구현했으면, maim() 영역으로 가자~ }

– public class Manager 소스 코드 (class)

package kosta.phone; import java.util.Scanner; public class Manager { Scanner sc = new Scanner(System.in); PhoneInfo[] arr = new PhoneInfo[10]; // PhoneInfo 클래스에 대한 10개의 객체를 만들었다. int count = 0; // 1. 프로그램을 구동할 세부적인 메서드(기능적인 부분)를 만들어준다. // 기능 : 전화번호 추가, 전화번호 출력, 전화번호 검색 public void addPhone() { System.out.print(“이름 : “); String name = sc.nextLine(); System.out.print(“전화번호 : “); String phoneNo = sc.nextLine(); System.out.print(“생년월일 : “); String birth = sc.nextLine(); arr[this.count++] = new PhoneInfo(name, phoneNo, birth); // 전화번호를 추가할 때마다 각각의 객체에 데이터를 추가한다. System.out.println(“전화번호가 등록되었습니다.”); } // 전화번호 추가 public void listPhone() { for (int i = 0; i < this.count; i++) { arr[i].show(); // PhoneInfo 클래스에 대한 show() 메서드를 호출 } } // 전화번호 출력 public void searchPhone() { System.out.print("이름 : "); String name = sc.nextLine(); // 찾고자하는 변수를 만들고, 입력한다. int idx = -1; // 문자열의 위치를 알기 위해서 만든 변수이다. // name 내가 쓴 문자열이 어디 있는지 모르기 때문에 하나씩 비교한다. for문으로.. for(int i = 0; i < count; i++) { PhoneInfo info = arr[i]; // 이미 생성된 객체를 변수에 넣는 것이므로, new 연산자를 사용하지 않아도 된다. if(name.equals(info.name)) { // i값은 배열의 위치를 알려준다. info.show(); idx = i; // 문자열의 존재여부를 확인 - 임시 변수! (0~9) break; // 나간다! } } if (idx == -1) { System.out.println("해당하는 정보를 찾을 수 없습니다."); } } // 전화번호 검색 //////////////////////////////////////////////////////////////////////////// // <<<<<<<<<<<<<<<<<<<<<<<<< Main() 영역 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // // 2. Manager 클래스를 Main() 영역에서 사용하기 위한 객체를 생성한다. // // < 객체를 반복적으로 생성하면 값에 영향을 주므로, Scanner 밑에 생성하는 것이 좋다. > // Manager m = new Manager(); // // // 3. 생성한 Manager 클래스에 대한 객체의 메서드(기능적인 부분)을 뼈대에 추가한다. // m.addPhone(); // m.listPhone(); // m.searchPhone(); //////////////////////////////////////////////////////////////////////////// // 4. 매서드를 하나씩 구현하기 위한 코드를 작성한다. // addPhone() {소스 코드 작성}, listPhone() {소스 코드 작성}, searchPhone() {소스 코드 작성} // 5. 전화번호의 추가와 검색에 필요한 자바 입력 API Scanner을 만든다. // Scanner sc = new Scanner(System.in); // 6. 전화번호부 관리프로그램의 상태와 기능을 담당하는 PhoneInfo 클래스의 객체를 생성한다. // PhoneInfo[] arr = new PhoneInfo[10]; // // 7.1 전화번호를 추가하는 메서드인 addPhone() {}의 소스 코드를 작성한다. // 모든 변수의 쓰임은 항상 통일해주는 것이 좋다. // String name = sc.nextLine();, String phoneNo = sc.nextLine();, String birth = sc.nextLine(); // 7.2 전화번호를 관리하는 arr[] 배열의 인덱스를 바꿔줄 수 있는 count를 선언한다. // int count = 0; // arr[count++] = new PhoneInfo(name, phoneNo, birth); // // 8. 전화번호부를 잔체출력하는 메서드인 listPhone() {}의 소스 코드를 작성한다. // for문을 사용하여, arr[]의 인덱스를 count의 멤버변수(필드)에 저장된 값에 따라서 결과를 출력한다. // 출력을 할때는, PhoneInfo 클래스의 show() 메서드를 사용한다. // <<<<<<<<<<<<< 향상된 for문을 사용하면 안된다. 각각의 인덱스에 접근할 수 없기 때문이다. >>>>>>>>>>> // 9. 전화번호부를 검색하는 메서드인 searchPhone() {}의 소스 코드를 작성한다. // idx = -1; 배열은 0부터 시작하므로, -1로 초기화한 변수를 하나 선언한다. // 이름에 대한 문자열을 비교하기 위해서, 각각의 객체의 값들을 info 변수에 넣어준다. PhoneInfo info = arr[i]; // equals 자바 APT를 통하여, if(name.equals(info.name))로 이름 문자열을 비교한다. // 있을 경우, PhoneInfo 클래스의 show 메서드로 info의 변수에 존재하는 대한 arr[idx]에 대한 데이터를 출력한다. // 없는 경우, idx의 초기값인 -1을 그대로 얻으므로써 없다라는 메세지를 출력한다. // -> 세부적인 기능을 구현했으면, 실행한다. }

– public class Main 소스 코드 (Main)

package kosta.phone; import java.util.Scanner; public class Main { public static void main(String[] args) { // 1. 자바 입력 API Scanner을 만든다. Scanner sc = new Scanner(System.in); Manager m = new Manager(); // Manager 클래스에 대한 객체를 하나 생성한다. // 2. 구현할 시스템의 뼈대를 만든다. // -> 뼈대 : 눈에 보이는 글씨와 사용자가 직접 입력하는 값 while (true) { System.out.println(“1.추가 2.전체 출력 3.검색 4.종료”); System.out.print(“메뉴의 번호 선택 : “); String menu = sc.nextLine(); // String 데이터형으로 받으면, 문자열을 선택하는 조건이 있어야한다. switch (menu) { // switch (menu) 입력되는 값에 따라서, case를 찾아간다. case “1”: // 1.추가 m.addPhone(); break; case “2”: // 2.전체출력 m.listPhone(); break; case “3”: // 3.검색 m.searchPhone(); break; case “4”: // 4.종료 System.out.println(“프로그램이 종료되었습니다.”); return; // 값을 반환하지 않으면, 종료의 역할을 수행한다. } } // -> 뼈대(눈에 보이는 글씨와 사용자가 직접 입력하는 값)를 구현했으면, Manager() 영역으로 가자~ } }

04장 연습문제

(연습문제 풀이 : https://wikidocs.net/157712#04)

Q1

다음 코드의 출력 결과는 무엇일까? (눈으로 해석하고 풀어보자.)

public class Sample { public static void main(String[] args) { String a = “write once, run anywhere”; if (a.contains(“wife”)) { System.out.println(“wife”); } else if (a.contains(“once”) && !a.contains(“run”)) { System.out.println(“once”); } else if (!a.contains(“everywhere”)) { System.out.println(“everywhere”); } else if (a.contains(“anywhere”)) { System.out.println(“anywhere”); } else { System.out.println(“none”); } } }

Q2

while문을 사용해 1부터 1000까지의 자연수 중 3의 배수의 합을 구해 보자.

Q3

while문 또는 for 문을 사용하여 다음과 같이 별( * )을 표시하는 프로그램을 작성해 보자.

* ** *** **** *****

Q4

for문을 사용해 1부터 100까지의 숫자를 출력해 보자.

Q5

A 학급에 총 10명의 학생이 있다. 이 학생들의 중간고사 점수는 다음과 같다.

int[] marks = {70, 60, 55, 75, 95, 90, 80, 80, 85, 100};

for each 문을 사용하여 A 학급의 평균 점수를 구해 보자.

Java 기초 클래스 – 연습문제(2)

글 작성자: 취업중인 피터팬

기본 환경

JDK : 1.8.0_261 버전 JRE : 1.8.0_261 버전 JAVA VERSION : 8 업데이트 261 Eclipse IDE VERSION : 2020-06버전

시나리오

Triangle 클래스을 만들어 밑변과 높이를 전달해 주고 삼격형의 높이를 구하는 클래스를 만들어라

다음과 같은 결과가 나와야 합니다.

public class QuTriangle { public static void main(String[] args) { Triangle t = new Triangle(); t.init(10, 17); //밑변10, 높이17로 초기화 System.out.println(“삼각형의 넓이 : ” + t.getArea()); t.setBottom(50);//밑변 50으로 변경 t.setHeight(14);//높이 14로 변경 System.out.println(“삼각형의 넓이 : ” + t.getArea()); } }

정답

package ex08Class; class Triangle{ //맴버 변수 double Bottom; double Height; //밑변과 높이를 초기화 하는 맴버메소드 void init(double bottom, double height) { this.Bottom = bottom; this.Height = height; } //삼각형의 넓이를 구하는 맴버메소드 double getArea() { double result = (Bottom * Height) / 2.0; return result; } //밑변을 설정 void setBottom(double bottom) { this.Bottom = bottom; } //높이를 설정 void setHeight(double height) { this.Height = height; } } public class QuTriangle { public static void main(String[] args) { Triangle t = new Triangle(); t.init(10, 17); //밑변10, 높이17로 초기화 System.out.println(“삼각형의 넓이 : ” + t.getArea()); t.setBottom(50);//밑변 50으로 변경 t.setHeight(14);//높이 14로 변경 System.out.println(“삼각형의 넓이 : ” + t.getArea()); } }

사실 생성자를 써야 하지만 init()함수로 초기화 해주었습니다. 생성자를 사용하는 것이 더 좋은 코드입니다.

728×90

[명품 JAVA] 4장 실습문제 (클래스와 객체)

반응형

[공지] 코딩, 솔루션, 포스팅 주제 관련

[4장 1번]

자바 클래스를 작성하는 연습을 해보자. 다음 main() 메소드를 실행하였을 때 예시와 같이 출력되도록 TV 클래스를 작성하라.

public static void main( String [] args) {

TV myTV = new TV( “LG” , 2017 , 32 ); //LG에서 만든 2017년 32인치

myTV.show();

}

LG에서 만든 2017년형 32인치 TV

[풀이]

package java_study4_1;

class TV {

private String brand;

private int year;

private int inch;

TV( String brand, int year, int inch) {

this .brand = brand;

this .year = year;

this .inch = inch;

}

public void show() {

System.out.println(brand+ “에서 만든 ” +year+ “년형 ” +inch+ “인치 TV” );

}

}

public class java_study4_1 {

public static void main( String [] args) {

// TODO Auto-generated method stub

TV myTV = new TV( “LG” , 2017 , 32 );

myTV.show();

}

}

[4장 2번]

Grade 클래스를 작성해보자. 3 과목의 점수를 입력받아 Grade 객체를 생성하고 성적 평균을 출력하는 main()과 실행 예시는 다음과 같다.

public static void main( String [] args) {

// TODO Auto-generated method stub

Scanner sc = new Scanner(System. in );

System.out.print( “수학, 과학, 영어 순으로 3개의 정수 입력 >> ” );

int math = sc.nextInt();

int science = sc.nextInt();

int english = sc.nextInt();

Grade me = new Grade(math, science, english);

System.out.println( “평균은 ” +me.average()); // average()는 평균을 계산하여 리턴

sc.close();

}

수학, 과학, 영어 순으로 3개의 정수 입력 >> 90 88 96

평균은 91

[Hint] Grade 클래스에 int 타입의 math, science, english 필드를 private로 선언하고, 생성자와 세 과목의 평균을 리턴하는 average() 메소드를 작성한다.

[풀이]

package java_study4_2;

import java.util.Scanner;

class Grade {

private int math;

private int science;

private int english;

Grade(int math, int science, int english) {

this .math = math;

this .science = science;

this .english = english;

}

public int average() {

return (math + science + english) / 3 ;

}

}

public class java_study4_2 {

public static void main( String [] args) {

// TODO Auto-generated method stub

Scanner sc = new Scanner(System. in );

System.out.print( “수학, 과학, 영어 순으로 3개의 정수 입력 >> ” );

int math = sc.nextInt();

int science = sc.nextInt();

int english = sc.nextInt();

Grade me = new Grade(math, science, english);

System.out.println( “평균은 ” +me.average());

sc.close();

}

}

[4장 3번]

노래 한 곡을 나타내는 Song 클래스를 작성하라. Song은 다음 필드로 구성된다.

– 노래의 제목을 나타내는 title

– 가수를 나타내는 artist

– 노래가 발표된 연도를 나타내는 year

– 국적을 나타내는 country

또한 Song 클래스에 다음 생성자와 메소드를 작성하라.

– 생성자 2개: 기본 생성자와 매개변수로 모든 필드를 초기화하는 생성자

– 노래 정보를 출력하는 show() 메소드

– main() 메소드에서는 1978년, 스웨덴 국적의 ABBA가 부른 “Dancing Queen”을

song 객체로 생성하고 show()를 이용하여 노래의 정보를 다음과 같이 출력하라.

1978년 스웨덴국적의 ABBA가 부른 Dancing Queen

[풀이]

package java_study4_3;

class Song {

private String title;

private String artist;

private int year;

private String country;

Song() {

this ( “title” , “artist” , 0000 , “country” );

}

Song( String title, String artist, int year, String country) {

this .title = title;

this .artist = artist;

this .year = year;

this .country = country;

}

public void show() {

System.out.println(year+ “년 ” +country+ “국적의 ” +artist+ “가 부른 ” +title);

}

}

public class java_study4_3 {

public static void main( String [] args) {

// TODO Auto-generated method stub

Song song = new Song( “Dancing Queen” , “ABBA” , 1978 , “스웨덴” );

song.show();

}

}

[4장 4번]

다음 멤버를 가지고 직사각형을 표현하는 Rectangle 클래스를 작성하라.

– int 타입의 x, y, width, height 필드: 사각형을 구성하는 점과 크기 정보

– x, y, width, height 값을 매개변수로 받아 필드를 초기화하는 생성자

– int square() : 사각형 넓이 리턴

– void show() : 사각형의 좌표와 넓이를 화면에 출력

– boolean contatins(Rectangle r) : 매개변수로 받은 r이 현 사각형 안에 있으면 true 리턴

– main() 메소드의 코드와 실행 결과는 다음과 같다

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를 포함합니다.” );

}

(2,2)에서 크기가 8×7인 사각형

s의 면적은 36

t는 r을 포함합니다.

[풀이]

package java_study4_4;

class Rectangle {

private int x;

private int y;

private int width;

private int height;

Rectangle(int x, int y, int width, int height) {

this .x = x;

this .y = y;

this .width = width;

this .height = height;

}

public void show() {

System.out.println( “(” +x+ “,” +y+ “)에서 크기가 ” +width+ “x” +height+ “인 사각형” );

}

public int square() {

return (width*height);

}

boolean contains(Rectangle r) {

if (x < r.x && y < r.y) if ((width+x) > (r.x+r.width) && (height+y) > (r.y+r.height))

return true ;

return false ;

}

}

public class java_study4_4 {

public static void main( String [] args) {

// TODO Auto-generated method stub

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를 포함합니다.” );

}

}

[4장 5번]

다음 설명대로 Circle 클래스와 CircleManager 클래스를 완성하라.

import java.util.Scanner;

class Circle {

private double x, y;

private int radius;

public Circle(double x, double y, int radius) {

_______________________________; //x, y, radius 초기화

}

public void show() {

_______________________________

}

}

public class CircleManager {

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner sc = ___________________;

Circle c[] = ______________; // 3개의 Circle 배열 선언

for(int i=0; i < _______; i ++) { System.out.print("x, y, radius >>”);

______________________; // x값 읽기.

______________________; // y값 읽기.

_______________________; // radius값 읽기.

c[i] = ____________________; // Circle 객체 생성

}

for(int i=0; i>3.0 3.0 5

x, y, radius >>2.5 2.7 6

x, y, radius >>5.0 2.0 4

(3.0,3.0)5

(2.5,2.7)6

(5.0,2.0)4

[풀이]

package java_study4_5;

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, y, radius 초기화

this .y =y;

this .radius = radius;

}

public void show() {

System.out.println( “(” + x + “,” + y + “)” + radius);

}

}

public class CircleManager {

public static void main( String [] args) {

// TODO Auto-generated method stub

Scanner sc = new Scanner(System. in );

Circle c[] = new Circle[ 3 ]; // 3개의 Circle 배열 선언

for (int i= 0 ; i < c.length; i ++) { System.out.print( "x, y, radius >>” );

double x = sc.nextDouble(); // x값 읽기.

double y = sc.nextDouble(); // y값 읽기.

int radius = sc.nextInt(); // radius값 읽기.

c[i] = new Circle(x, y, radius); // Circle 객체 생성

}

for (int i= 0 ; i>3.0 3.0 5

x, y, radius >>2.5 2.7 6

x, y, radius >>5.0 2.0 4

가장 면적인 큰 원은 (2.5,2.7)6

[풀이]

package java_study4_6;

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, y, radius 초기화

this .y =y;

this .radius = radius;

}

public void show() {

System.out.println( “(” + x + “,” + y + “)” + radius);

}

public int getRadius() {

return radius;

}

}

public class CircleManager {

public static void main( String [] args) {

// TODO Auto-generated method stub

Scanner sc = new Scanner(System. in );

Circle c[] = new Circle[ 3 ]; // 3개의 Circle 배열 선언

int max= 0 ;

for (int i= 0 ; i < c.length; i ++) { System.out.print( "x, y, radius >>” );

double x = sc.nextDouble(); // x값 읽기.

double y = sc.nextDouble(); // y값 읽기.

int radius = sc.nextInt(); // radius값 읽기.

c[i] = new Circle(x, y, radius); // Circle 객체 생성

}

for (int i= 0 ; i>1

날짜(1~30)?1

할일(빈칸없이입력)?자바공부

할일(입력:1, 보기:2, 끝내기:3) >>2

날짜(1~30)?1

1일의 할 일은 자바공부입니다.

할일(입력:1, 보기:2, 끝내기:3) >>3

프로그램을 종료합니다.

[Hint] MonthSchedule에는 생성자, input(), view(), finish(), run() 메소드를 만들고 main()에서 다음과 같이 호출하여 실행하고 run()에서 메뉴를 출력하고 처리한다.

MonthSchedule april = new MonthSchedule( 30 ); // 4월달의 할 일

april.run();

[풀이]

package java_study4_7;

import java.util.Scanner;

class Day {

private String work; // 하루의 할 일을 나타내는 문자열

public void set( String work) { this .work = work; }

public String get() { return work; }

public void show() {

if (work == null ) System.out.println( “없습니다.” );

else System.out.println(work + “입니다.” );

}

}

public class MonthSchedule {

private Scanner sc;

private Day days[];

MonthSchedule(int day) {

this .days = new Day[day];

for (int i= 0 ; i 30 ) { // 0~29

System.out.println( “날짜를 잘못 입력하였습니다.” );

return ;

}

days[day].set(work);

}

private void view() {

System.out.print( “날짜(1~30)?” );

int day = sc.nextInt();

day–;

if (day < 0 || day > 30 ) { // 0~29

System.out.println( “날짜를 잘못 입력하였습니다.” );

return ;

}

System.out.print((day+ 1 )+ “일의 할 일은 ” );

days[day].show();

}

private void finish() {

System.out.println( “프로그램을 종료합니다.” );

sc.close();

}

public void run() {

System.out.print( “이번달 스케쥴 관리 프로그램.” );

while ( true ) {

System.out.println();

System.out.print( “할일(입력:1, 보기:2, 끝내기:3) >>” );

int select = sc.nextInt();

switch(select) {

case 1 : input(); break ;

case 2 : view(); break ;

case 3 : finish(); return ;

}

}

}

public static void main( String [] args) {

// TODO Auto-generated method stub

MonthSchedule april = new MonthSchedule( 30 ); // 4월달의 할 일

april.run();

}

}

[4장 8번]

이름(name), 전화번호(tel) 필드와 생성자 등을 가진 Phone 클래스를 작성하고, 실행 예시와 같이 작동하는 PhonBook 클래스를 작성하라.

인원수 >> 3

이름과 전화번호(이름과 번호는 빈 칸없이 입력)>>황기태 777-7777

이름과 전화번호(이름과 번호는 빈 칸없이 입력)>>나명품 999-9999

이름과 전화번호(이름과 번호는 빈 칸없이 입력)>>최자바 333-1234

저장되었습니다…

검색할 이름 >>황기순

황기순이 없습니다.

검색할 이름 >>최자바

최자바의 번호는 333-1234 입니다.

검색할 이름 >>그만

[Hint] PhoneBook 클래스에서 저장할 사람의 수를 입력받고, Phone 개게 배열을 생성한다. 한 사람의 정보는 하나의 Phone 객체에 저장한다. 7번 정답을 참고하기 바란다. 문자열 a와 b가 같은지 비교할 때 a.equals(b)가 참인지로 판단한다.

[풀이]

package java_study4_8;

import java.util.Scanner;

class Phone {

private String name;

private String tel;

Phone( String name, String tel) {

this .name = name;

this .tel = tel;

}

public String getName() {

return name;

}

public String getTel() {

return tel;

}

}

public class PhoneBook {

public static void main( String [] args) {

// TODO Auto-generated method stub

Scanner sc = new Scanner(System. in );

Phone phone[];

int i;

System.out.print( “인원수 >> ” );

int num = sc.nextInt();

phone = new Phone[num];

for (i= 0 ; i>” );

String name = sc.next();

String tel = sc.next();

phone[i] = new Phone(name, tel);

}

System.out.println( “저장되었습니다…” );

while ( true ) {

System.out.print( “검색할 이름 >>” );

String name = sc.next();

for (i= 0 ; i> 5 7 *

35

[풀이]

package java_study4_11;

import java.util.Scanner;

class Add {

private int a;

private int b;

public void setValue(int a, int b) {

this .a = a;

this .b = b;

}

public int calculate() {

return a+b;

}

}

class Sub {

private int a;

private int b;

public void setValue(int a, int b) {

this .a = a;

this .b = b;

}

public int calculate() {

return a-b;

}

}

class Mul {

private int a;

private int b;

public void setValue(int a, int b) {

this .a = a;

this .b = b;

}

public int calculate() {

return a*b;

}

}

class Div {

private int a;

private int b;

public void setValue(int a, int b) {

this .a = a;

this .b = b;

}

public int calculate() {

return a/b;

}

}

public class java_study4_11 {

public static void main( String [] args) {

// TODO Auto-generated method stub

Scanner sc = new Scanner(System. in );

int result= 0 ;

System.out.print( “두 정수와 연산자를 입력하시오 >> ” );

int a = sc.nextInt();

int b = sc.nextInt();

char c = sc.next().charAt( 0 );

switch(c) {

case ‘+’ :

Add add = new Add();

add.setValue(a, b);

result = add.calculate();

break ;

case ‘-‘ :

Sub sub = new Sub();

sub.setValue(a, b);

result = sub.calculate();

break ;

case ‘*’ :

Mul mul = new Mul();

mul.setValue(a, b);

result = mul.calculate();

break ;

case ‘/’ :

Div div = new Div();

div.setValue(a, b);

result = div.calculate();

break ;

}

System.out.println(result);

sc.close();

}

}

[4장 12번]

간단한 콘서트 예약 시스템을 만들어보자. 다수의 클래스를 다루고 객체의 배열을 다루기에는 아직 자바 프로그램 개발이 익숙하지 않은 초보자에게 다소 무리가 있을 것이다. 그러나 반드시 넘어야 할 산이다. 이 도전을 통해 산을 넘어갈 수 있는 체력을 키워보자. 예약 시스템의 기능은 다음과 같다.

– 공연은 하루에 한 번 있다.

– 좌석은 S석, A석, B석으로 나뉘며, 각각 10개의 좌석이 있다.

– 예약 시스템의 메뉴는 “예약”, “조회”, “취소”, “끝내기”가 있다.

– 예약은 한 자리만 가능하고, 좌석 타입, 예약자 이름, 좌석 번호를 순서대로 입력받아 예약한다.

– 조회는 모든 좌석을 출력한다.

– 취소는 예약자의 이름을 입력받아 취소한다.

– 없는 이름, 없는 번호, 없는 메뉴, 잘못된 취소 등에 대해서 오류 메시지를 출력하고 사용자가 다시 시도하도록 한다.

명품콘서트홀 예약 시스템입니다.

예약:1, 조회:2, 취소:3, 끝내기:4 >> 1

좌석구분 S(1), A(2), B(3)>>1

S>> ___ ___ ___ ___ ___ ___ ___ ___ ___ ___

이름>>황기태

번호>>1

예약:1, 조회:2, 취소:3, 끝내기:4 >> 1

좌석구분 S(1), A(2), B(3)>>2

A>> ___ ___ ___ ___ ___ ___ ___ ___ ___ ___

이름>>김효수

번호>>5

예약:1, 조회:2, 취소:3, 끝내기:4 >> 2

S>> 황기태 ___ ___ ___ ___ ___ ___ ___ ___ ___

A>> ___ ___ ___ ___ 김효수 ___ ___ ___ ___ ___

B>> ___ ___ ___ ___ ___ ___ ___ ___ ___ ___

<<<조회를 완료하였습니다.>>>

예약:1, 조회:2, 취소:3, 끝내기:4 >> 3

좌석 S:1, A:2, B:3>>2

A>> ___ ___ ___ ___ 김효수 ___ ___ ___ ___ ___

이름>>김효수

예약:1, 조회:2, 취소:3, 끝내기:4 >> 2

S>> 황기태 ___ ___ ___ ___ ___ ___ ___ ___ ___

A>> ___ ___ ___ ___ ___ ___ ___ ___ ___ ___

B>> ___ ___ ___ ___ ___ ___ ___ ___ ___ ___

<<<조회를 완료하였습니다.>>>

예약:1, 조회:2, 취소:3, 끝내기:4 >> 4

[풀이]

package java_study4_12;

import java.util.Scanner;

class Concert{

private String S[];

private String A[];

private String B[];

private Scanner sc;

Concert() {

sc = new Scanner(System. in );

S = new String [ 10 ];

A = new String [ 10 ];

B = new String [ 10 ];

for (int i= 0 ; i>” );

Concert.printSeat(S);

System.out.print( “A>>” );

Concert.printSeat(A);

System.out.print( “B>>” );

Concert.printSeat(B);

System.out.println( “<<<조회를 완료하였습니다.>>>” );

}

public void choiceSeat() { //좌석 선택(S, A, B) 메소드

while ( true ) {

System.out.print( “좌석구분 S(1), A(2), B(3)>>” );

int select = sc.nextInt();

switch(select) {

case 1 :

System.out.print( “S>>” );

printSeat(S);

inputSeat(S);

return ;

case 2 :

System.out.print( “A>>” );

printSeat(A);

inputSeat(A);

return ;

case 3 :

System.out.print( “B>>” );

printSeat(B);

inputSeat(B);

return ;

default:

System.out.println( “다시 입력해 주세요.” );

}

}

}

public void inputSeat( String seat[]) { //좌석에 이름값 넣는 메소드

System.out.print( “이름>>” );

String name = sc.next();

while ( true ) {

System.out.print( “번호>>” );

int num = sc.nextInt();

num–;

if (seat[num].equals( “___” )) {

seat[num] = name;

break ;

}

else {

System.out.println( “다른 좌석을 선택해 주세요.” );

}

}

}

public void d_choiceSeat() {

while ( true ) {

System.out.print( “좌석 S:1, A:2, B:3>>” );

int select = sc.nextInt();

switch(select) {

case 1 :

System.out.print( “S>>” );

printSeat(S);

delete (S);

return ;

case 2 :

System.out.print( “A>>” );

printSeat(A);

delete (A);

return ;

case 3 :

System.out.print( “B>>” );

printSeat(B);

delete (B);

return ;

default:

System.out.println( “다시 입력해 주세요.” );

}

}

}

public void delete ( String seat[]) {

System.out.print( “이름>>” );

String name = sc.next();

for (int i= 0 ; i> ” );

int select = sc.nextInt();

switch(select) {

case 1 :

concert.choiceSeat();

break ;

case 2 :

concert.allPrint();

break ;

case 3 :

concert.d_choiceSeat();

break ;

case 4 :

sc.close();

return ;

default :

System.out.println( “다시 입력해 주세요.” );

}

}

}

}

반응형

JAVA1_day15 | 클래스 Class 연습문제 (1)

문제3. “인스턴스 메서드 입니다.” 라는 출력문을 보여주는 클래스 showInfo()

문제4. 정수 2개를 전달받아(인자,argument) 두 수를 더한 결과를 return해주는 클래스 sum()

문제5. 이름(문자) 1개를 전달받아 “나는 이름 입니다.” 라는 출력문을 보여주는 인스턴스 showName()

문제6. 세 개의 정수를 전달받아, 최대값과 최소값을 구하는 메서드를 만들어보자.

문제7. 국어, 영어, 수학 3과목의 점수를 입력받아, 총점과 평균을 구하는 메서드를 만들어보자.

“국어, 영어, 수학의 점수를 입력해주세요: ”

System . out . print ( “국어, 영어, 수학의 점수를 입력해주세요: ” );

문제8. char[] 배열을 전달받아 출력하는 printWord() 메서드와 배열 속의 공백(‘ ‘) 문자를 ‘,’ 로 대체하는 replace()메서드를 작성해보자.

// 문자형 배열은 바로 그 값을 나타낸다.

// 문자형 배열은 바로 그 값을 나타낸다.

# 설명

Line 37: Scanner를 이용하여 입력받은 문자열 str의 길이만큼 문자형 배열 char[] arr를 생성해준다.

Line 38~41: arr의 길이만큼 for문을 돌아 charAt(index)를 통하여 입력받은 문자열 하나씩 arr 배열에 입력해준다.

Line 9: 정수형 배열과는 다르게 문자형 배열은 변수값인 arr를 그대로 출력할 경우 주소값이 아닌 데이터값이 그대로 출력된다.

그러나 문자열 다음에 출력하게 되면 그때는 주소값이 나온다.

Line 12~17: 인자로 받은 arr의 길이만큼 for문을 돌며 arr의 값이 공백일 경우 즉, arr[i] == ‘ ‘ 일 때 그 값을 , 로 변경해준다.

<명품 JAVA Programming> – Chapter4 연습문제(1, 2, 3, 4, 5, 6)

반응형

1. 자바 클래스를 작성하는 연습을 해보자. 다음 main()메소드를 실행하였을 때 예시와 같이 출력되도록 TV 클래스를 작성하라.

package chapter4; //퍼블릭 클래스명은 TV 대신 Chapter4_1_TV public class TV { private String name; private int year, size; public TV(String name, int year, int size) { this.name = name; this.year = year; this.size = size; } public void show() { System.out.println(this.name + “에서 만든 ” + this.year + “년형 ” + this.size + “인치 TV”); } public static void main(String[] args) { TV myTv = new TV(“LG”, 2017, 32); myTv.show(); } }

2. Grade 클래스를 작성해보자. 3 과목의 점수를 입력받아 Grade 객체를 생성하고 성적 평균을 출력하는 main()과 실행 예시는 다음과 같다.

package chapter4; import java.util.Scanner; public class Grade { private int math, science, english; public Grade(int math, int science, int english) { this.math = math; this.science = science; this.english = english; } public int average() { return (this.math + this.science + this.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()); scanner.close(); } }

3. 노래 한 곡을 나타내는 Song 클래스를 작성하라. Song은 다음 필드로 구성된다.

package chapter4; public class Song { private String title, artist, country; private int year; public Song() {}; public Song(String title, String artist, String country, int year ) { this.title = title; this.artist = artist; this.country = country; this.year = year; } public void show() { System.out.print(year + “년 “); System.out.print(country + “국적의 “); System.out.print(artist + “가 부른 “); System.out.println(title); } public static void main(String[] args) { Song song = new Song(“Dancing Queen”, “ABBA”, “스웨덴”, 1978); song.show(); } }

4.다음 멤버를 가지고 직사각형을 표현하는 Rectangle 클래스를 작성하라.

package chapter4; public class Rectangle { private int 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; } public int square() { return this.width * this.height; } public void show() { System.out.print(“(” + this.x + “,” + this.y + “) “); System.out.println(“에서 크기가 ” + width + “x” + height + “인 사각형”); } public boolean contains(Rectangle r) { if(this.x < r.x && this.y < r.x) if((this.x + this.width > r.x + r.width) && (this.y + this.height > r.y + r.height)) return true; 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. 다음 설명대로 Circle 클래스와 CircleManager 클래스를 완성하라.

package chapter4; import java.util.Scanner; class Circle { private double x, y; private int radius; public Circle(double x, double y, int radius) { //x, y, radius 초기화 this.x = x; this.y = y; this.radius = radius; } public void show() { System.out.println(“(” + x + “,” + y + “) ” + radius); } } public class CircleManager { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Circle c[] = new Circle[3]; //3개의 Circle 배열 선언 for(int i = 0; i < c.length; i++) { System.out.print("x, y, radius >>”); double x = scanner.nextDouble(); //x값 읽기 double y = scanner.nextDouble(); //y값 익기 int r = scanner.nextInt(); //반지름 읽기 c[i] = new Circle(x, y, r); //Circle 객체 생성 } for(int i = 0; i < c.length; i++) c[i].show(); //모든 Circle 객체 출력 scanner.close(); } } 6. 앞의 5번 문제는 정답이 공개되어 있다. 이 정답을 참고하여 Circle 클래스와 Circlemanager 클래스를 수정하여 다음 실행 결과처럼 되게 하라. package chapter4; import java.util.Scanner; class Circle2 { private double x, y; private int radius; public Circle2(double x, double y, int radius) { //x, y, radius 초기화 this.x = x; this.y = y; this.radius = radius; } public void show() { System.out.println("가장 면적이 큰 원은 (" + x + "," + y + ") " + radius); } public int square() { //면적을 구하는 메소드 return this.radius * this.radius; } } public class CircleManager2 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int max, j = 0; Circle2 c[] = new Circle2[3]; //3개의 Circle 배열 선언 for(int i = 0; i < c.length; i++) { System.out.print("x, y, radius >>”); double x = scanner.nextDouble(); //x값 읽기 double y = scanner.nextDouble(); //y값 익기 int r = scanner.nextInt(); //반지름 읽기 c[i] = new Circle2(x, y, r); //Circle 객체 생성 } max = c[0].square(); //첫 번째 객체를 최대로 가정 for(int i = 1; i < c.length; i++) { if (c[i].square() > max) j = i; } c[j].show(); //면적이 가장 큰 Circle 객체 출력 scanner.close(); } }

반응형

자바 클래스 문제 | Java – 13. 클래스 134 개의 가장 정확한 답변

당신은 주제를 찾고 있습니까 “자바 클래스 문제 – Java – 13. 클래스“? 다음 카테고리의 웹사이트 you.dianhac.com.vn 에서 귀하의 모든 질문에 답변해 드립니다: https://you.dianhac.com.vn/blog. 바로 아래에서 답을 찾을 수 있습니다. 작성자 생활코딩 이(가) 작성한 기사에는 조회수 10,380회 및 좋아요 81개 개의 좋아요가 있습니다.

자바 클래스 문제 주제에 대한 동영상 보기

여기에서 이 주제에 대한 비디오를 시청하십시오. 주의 깊게 살펴보고 읽고 있는 내용에 대한 피드백을 제공하세요!

d여기에서 Java – 13. 클래스 – 자바 클래스 문제 주제에 대한 세부정보를 참조하세요

생활코딩은 일반인에게 프로그래밍을 알려주는 활동입니다. 더 많은 정보를 원하시면 http://opentutorials.org/course/1를 방문해주세요.

자바 클래스 문제 주제에 대한 자세한 내용은 여기를 참조하세요.

JAVA (자바) – 클래스 연습 문제 모음 – (1) – 개발이 하고 싶어요

JAVA (자바) – 클래스 연습 문제 모음 – (1) 문제 1 – 다음을 만족하는 Student 클래스를 작성하시오. · String형의 학과와 정수형의 학번을 필드로 …

+ 여기에 표시

Source: iu-corner.tistory.com

Date Published: 4/27/2022

View: 8882

[22] 클래스를 활용한 연습 문제 – velog

– public Manager 소스 코드 (). package kosta.phone; import java.util.Scanner; public Manager { Scanner sc = new Scanner(System.

+ 여기에 더 보기

Source: velog.io

Date Published: 12/17/2021

View: 7746

04장 연습문제 – 점프 투 자바

다음 코드의 출력 결과는 무엇일까? (눈으로 해석하고 풀어보자.) public Sample { public static vo main(String[] args) …

+ 여기에 더 보기

Source: wikidocs.net

Date Published: 7/13/2021

View: 6267

Java 기초 클래스 – 연습문제(2) – 자유롭게 사는 – Tistory

기본 환경 JDK : 1.8.0_261 버전 JRE : 1.8.0_261 버전 JAVA VERSION : 8 업데이트 261 Eclipse IDE VERSION : 2020-06버전 시나리오 Triangle …

+ 여기에 보기

Source: kkungchan.tistory.com

Date Published: 8/5/2022

View: 3907

[명품 JAVA] 4장 실습문제 (클래스와 객체) – 낭람

[공지] 코딩, 솔루션, 포스팅 주제 관련 [4장 1번] 자바 클래스를 작성하는 연습을 해보자. 다음 main() 메소드를 실행하였을 때 예시와 같이 출력 …

+ 여기에 자세히 보기

Source: security-nanglam.tistory.com

Date Published: 6/12/2021

View: 6894

JAVA1_day15 | 클래스 Class 연습문제 (1) – UBANGE

문제1. 10을 return해주는 클래스 getNumber() … 문제3. “인스턴스 메서드 입니다.” 라는 출력문을 보여주는 클래스 … import java.util.Scanner;.

+ 여기에 더 보기

Source: ubange.tistory.com

Date Published: 2/15/2021

View: 2945

– Chapter4 연습문제(1, 2, 3, 4, 5, 6)

1. 자바 클래스를 작성하는 연습을 해보자. 다음 main()메소드를 실행하였을 때 예시와 같이 출력되도록 TV 클래스를 작성하라. package chapter4; …

+ 여기에 더 보기

Source: kiffblog.tistory.com

Date Published: 6/28/2022

View: 5347

자바 4장 연습문제(클래스와 객체)-2 – 개발자 D 개발 노트

문제) — 내풀이는 밑에. 4-5) 다음 설명대로 Circle 클래스와 CircleManager 클래스를 완성하라. import java.util.Scanner; Circle{ private …

+ 여기에 보기

Source: cordingdoah.tistory.com

Date Published: 10/24/2022

View: 6551

[Java] 연습문제 – 붕어의 코딩 공부 기록

06-3의 예제를 참고하여 카드가 생성될 때마다 카드 번호가 자동으로 증가할 수 있도록 카드 클래스를 만들고 생성해보자. ​. ​.

+ 더 읽기

Source: poew.tistory.com

Date Published: 7/10/2021

View: 3200

자바 클래스 문제

다음 main() 메소드를 실행하였을 때 예시와 같이 출력Nov, · JAVA (자바)클래스 연습 문제 모음(1) 문제다음을 만족하는 Student 클래스를 작성하시오.

+ 여기에 더 보기

Source: lasgavias.es

Date Published: 10/9/2022

View: 9313

주제와 관련된 이미지 자바 클래스 문제

주제와 관련된 더 많은 사진을 참조하십시오 Java – 13. 클래스. 댓글에서 더 많은 관련 이미지를 보거나 필요한 경우 더 많은 관련 기사를 볼 수 있습니다.

Java – 13. 클래스

주제에 대한 기사 평가 자바 클래스 문제

Author: 생활코딩

Views: 조회수 10,380회

Likes: 좋아요 81개

Date Published: 2014. 7. 12.

Video Url link: https://www.youtube.com/watch?v=GUk7Huv2Doc

JAVA (자바) – 클래스 연습 문제 모음 – (1)

반응형 JAVA (자바) – 클래스 연습 문제 모음 – (1) 문제 1 – 다음을 만족하는 Student 클래스를 작성하시오. · String형의 학과와 정수형의 학번을 필드로 선언 · Student 클래스의 main() 메소드에서 Student 객체를 생성하여 학과와 학번 필드에 적당한 값을 입력 후 출력 문제 – 2. 위에서 구현한 Student 클래스를 다음을 만족하도록 기능을 추가하여 작성하시오. · 필드를 모두 private로 하고, getter와 setter를 구현하고 · Student 클래스의 main() 메소드에서 Student 객체를 생성하여 setter를 사용하여 학과와 학번 필드에 적당한 값을 입력 후 출력 문제 – 3. 다음에 구현된 Circle 클래스를 참고로 다음을 만족하는 Cylinder 클래스를 작성하시오. · 원통을 나타내는 Cylinder 클래스는 Circle형의 원과 실수형의 높이를 필드로 선언 · 메소드 getVolume()은 원통의 부피를 반환 · Cylinder 클래스의 main() 메소드에서 반지름이 2.8, 높이가 5.6의 원통의 부피를 출력 · 다음은 원을 나타내는 클래스 Circle public class Circle { public double radius; public static double PI = 3.141592; //생성자 구현 public Circle(double radius) { this.radius = radius; } //현재 반지름을 사용하여 원의 면적을 구하는 메소드 public double getArea() { return radius * radius * PI; } } 문제 4 – 위에서 구현한 Cylinder를 다음 조건에 맞도록 기능을 추가하여 작성하시오. · 다음과 같은 객체 생성이 가능하도록 생성자를 구현 ㆍ Cylinder cd = new Cylinder(new Circle(2.8), 5.6); 문제 5 – 다음을 만족하는 클래스 SalaryMan을 작성하시오. · 필드 salary는 월 급여액를 저장하며, int형으로 초기 값으로 1000000 저장 · 메소드 getAnnualGross()는 연봉을 반환하는 메소드로 월급에 보너스 500%로 계산 · 기본 생성자에서 필드 salary의 초기 값을 사용하며, 정수형 인자인 생성자에서 인자가 월 급여액으로 지정 · 다음과 같이 객체를 생성하여 메소드 getAnnualGrass()를 호출하여 출력 System.out.println(new SalaryMan().getAnnualGross()); System.out.println(new SalaryMan(2_000_000).getAnnualGross()); 문제 6 – 다음을 만족하는 클래스 Account를 작성하시오. · 다음의 2 개의 필드를 선언 private String owner; private long balance; · 위 모든 필드에 대한 getter와 setter의 구현 · 위 모든 필드를 사용하는 가능한 모든 생성자의 구현 문제 7 – 위에서 구현된 클래스 Account에서 다음 기능을 추가하여 작성하시오. · 메소드 deposit()의 헤드는 다음과 같으며 인자인 금액을 저축하는 메소드 public long deposit(long amount) · 메소드 withdraw()의 헤드는 다음과 같으며 인자인 금액을 인출하는 메소드 public long withdraw(long amount) · Account 클래스의 main() 메소드에서 Account 객체를 생성하여 적당한 저축과 인출을 수행한 후 잔금을 출력 문제 8 – 위에서 구현된 메소드 withdraw()를 다음 조건에 맞게 다시 작성하시오. · 인출 상한 금액은 잔액까지로 하며, 이 경우 이러한 상황을 출력 · 클래스 AccountTest의 main() 메소드에서 인출 상한 이상의 금액을 인출하려는 메소드를 호출하여 출력 문제 – 9. 다음을 만족하는 클래스 Rectangle을 작성하시오. · 사각형의 가로와 세로로 객체를 생성하는 생성자 · 면적을 반환하는 메소드 getArea(), 둘레를 반환하는 메소드 getCircumference(), · 다음과 같이 클래스 Rectangle 이용 Rectangle rc = new Rectangle(3.82, 8.65); System.out.println(“면적: ” + rc.getArea()); System.out.println(“둘레: ” + rc.getCircumference()); 문제 – 10. 다음을 만족하는 클래스 Computer를 작성하시오. · 다음을 상수 필드로 선언 public … String[] osType = {“원도7”, “애플 OS X”, “안드로이드”}; · 다음과 같은 클래스 Computer의 객체의 사용 결과에 적합하도록 생성자와 메소드 구현 Computer pc = new Computer(0, 16); Computer apple = new Computer(1, 32); Computer galaxy = new Computer(2, 16); pc.print(); apple.print(); galaxy.print(); 운영체제: 원도7, 메인메모리: 16 운영체제: 애플 OS X, 메인메모리: 32 운영체제: 안드로이드, 메인메모리: 16 public cla 소스 코드 문제 1 + 2 package ex1; import java.util.Scanner; class StudentEx2{ private String name; private int id; void setName(String name) { // setter 네임 this.name = name; } String getName() { // getter id return this.name+” 학과”; } void setId(int id) { this.id = id; } int getId() { return this.id; } } public class StudentEx1 { public static void main(String[] args) { /* * 다음을 만족하는 Student 클래스를 작성하시오 * String 형의 학과와 정수형의 학번을 필드로 선언 * Student 클래스의 main()메소드에서 Student 객체를 생성하여 학과와 학번 필드에 * 적당한 값을 입력한 후 출력 * 2. 위에서 구현한 Student 클래스를 다음을 만족하도록 기능을 추가하여 작성하시오. 필드를 모두 private로 하고, getter와 setter를 구현하고 Student 클래스의 main() 메소드에서 Student 객체를 생성하여 setter를 사용하여 학과와 학번 필드에 적당한 값을 입력 후 출력 */ Scanner sc = new Scanner(System.in); StudentEx2 student1 = new StudentEx2(); System.out.println(“—회원가입—“); System.out.print(“학과 입력 :”); String name = sc.next(); student1.setName(name); System.out.print(“학번 입력 :”); int id = sc.nextInt(); student1.setId(id); System.out.println(“학생1의 학과 :”+student1.getName()+”, 학번 :”+student1.getId()); } } 문제 3+4 package ex1; public class Circle { public double radius; // 필드(==인스턴스)변수 선언 public static double PI = 3.141592; // 원주율 // 생성자 구현 public Circle(double radius) { this.radius = radius; } // 기능 구현 public double getArea() { return radius * radius * PI; // 원의 면적을 구하는 공식 반지름*반지름*파이 } } package ex1; public class Cylinder { Circle cir; double height; public Cylinder(Circle cir,double height) { // TODO Auto-generated constructor stub this.cir=cir; this.height=height; } // 생성자 구현 public double Volum() { return cir.getArea()*height; // 반지름과 높이를 곱함.. } public static void main(String[] args) { // 반지름이 2.8 , 높이가 5.6의 원통의 부피를 출력 Circle cp = new Circle(2.8); // 반지름 2.8 Cylinder cd = new Cylinder(new Circle(2.8), 5.6); // Circle 생성자의 2.8, Cylinder 5.6 double height = 5.6; // radius 2.8 height 5.6 // 부피 구하는 법 : 원의 면적 * 높이 . >> 면적은 반지름+반지름+파이 파이먹고싶다 System.out.println(“부피 : “+(cp.getArea()*height)); System.out.println(cd.Volum()); // 동일한 결과 } } /* * 3. 다음에 구현된 Circle 클래스를 참고로 다음을 만족하는 Cylinder 클래스를 작성하시오. · 원통을 나타내는 Cylinder 클래스는 Circle형의 원과 실수형의 높이를 필드로 선언 · 메소드 getVolume()은 원통의 부피를 반환 · Cylinder 클래스의 main() 메소드에서 반지름이 2.8, 높이가 5.6의 원통의 부피를 출력 · 다음은 원을 나타내는 클래스 Circle 4. 위에서 구현한 Cylinder를 다음 조건에 맞도록 기능을 추가하여 작성하시오. · 다음과 같은 객체 생성이 가능하도록 생성자를 구현 ㆍ Cylinder cd = new Cylinder(new Circle(2.8), 5.6); */ 문제 5 package Salary; public class SalaryMan { int salary; //월 급여 액 저장 초기값 1,000,000 저장 SalaryMan(){ this.salary = 1000000; } SalaryMan(int salary){ // 생성자에서 인자 월 급여액을 지정하기 위한 재정의 this.salary=salary; } public int getAnnualGross() { // 연봉.. 연봉은 월 * 12 인데 // 보너스 500%를 수령해야 하니까 5.0을 곱해야하지만 int 정수형이므로 5만 곱하고 return (this.salary*12)+(this.salary*5); // 연봉 + 500% 보너스 수령 // 연봉 리턴 } public static void main(String[] args) { SalaryMan user = new SalaryMan(); user.salary = 1500000; // 연봉 1800만 * 보너스 750만 // 최저도 못받는 인생인데 보너스가 쎄네 System.out.println(user.getAnnualGross()); System.out.println(); System.out.println(new SalaryMan().getAnnualGross()); System.out.println(new SalaryMan(2000000).getAnnualGross()); } } /* 5. 다음을 만족하는 클래스 SalaryMan을 작성하시오. · 필드 salary는 월 급여액를 저장하며, int형으로 초기 값으로 1000000 저장 · 메소드 getAnnualGross()는 연봉을 반환하는 메소드로 월급에 보너스 500%로 계산 · 기본 생성자에서 필드 salary의 초기 값을 사용하며, 정수형 인자인 생성자에서 인자가 월 급여액으로 지정 · 다음과 같이 객체를 생성하여 메소드 getAnnualGrass()를 호출하여 출력 System.out.println(new SalaryMan().getAnnualGross()); System.out.println(new SalaryMan(2_000_000).getAnnualGross()); */ 문제 6 + 7 + 8 package Account; import java.util.Scanner; class Account { private String owner; private long balance; Account(){ // default 생성자 } Account(String owner){ this.owner = owner; } Account(long balance){ this.balance=balance; } Account(String owner, long balance){ this.owner = owner; this.balance = balance; } void setOwner(String owner) { this.owner = owner; } String getOwner() { return this.owner; } void setBalance(long balance) { this.balance = balance; } long getBalance() { return this.balance; } public long deposit(long amount) { // 인자인 금액을 저축하는 기능 System.out.println(amount+”만큼 입금 합니다.”); return this.balance+=amount; //저장 } public long withdraw(long amount) { // 입력한 금액만큼 인출한 기능 Scanner sc = new Scanner (System.in); long money = amount; // 새로운 money 변수를 선언 System.out.println(“현재 고객님은 “+this.balance+”원 까지 인출할 수 있습니다.”); if(this.balance < amount ) { // 현재 값이 입력 값보다 적다면 System.out.println("잔액이 부족하여 인출하실 수 없습니다."); System.out.println("가진 금액을 모두 출금 하시겠습니까? y/n"); String se[] = {"y","n"}; String sel = sc.next(); if(sel.equals(se[0])) { money = this.balance; // 현재 돈을 money값에 대입 } } System.out.println(money+"만큼 인출 합니다."); return this.balance -= money; // money값 } void show() { System.out.println(this.owner+"님은 현재 "+this.balance+"원을 가지고 있습니다."); } } public class Main { public static void main(String[] args) { Scanner sc = new Scanner (System.in); Account player = new Account(); // 생성자 System.out.print("사용자 성함을 입력하세요 :"); String owner = sc.next(); player.setOwner(owner); System.out.print("사용자의 잔액은 얼만큼 있는지 적으세요. :"); long balance = sc.nextLong(); player.setBalance(balance); player.show(); System.out.println("얼만큼 저축 하시겠습니까?"); int amo = sc.nextInt(); player.deposit(amo); player.show(); System.out.println("얼마를 인출 하시겠습니까?"); amo = sc.nextInt(); player.withdraw(amo); player.show(); } } 9 - package Rectangle; public class Rectangle { double width; double length; Rectangle(double width, double length){ this.width=width; this.length=length; } double getArea() { // 면적 (가로*세로) return this.width * this.length; } double getCircumference() { // 둘레 (가로+높이)*2 return (this.width+this.length)*2 ; } public static void main(String[] args) { // 사각형의 가로와 세로로 객체를 생성하는 생성자 // 면적을 반환하는 메소드 getArea(), // 둘레를 반환하는 메소드 getCircumference(), // 다음과 같이 클래스 Rectangle 이용 // Rectangle rc = new Rectangle(3.82, 8.65); // System.out.println("면적 : "+rc.getArea()); // System.out.println("둘레 : "+rc.getCircumference()); Rectangle rc = new Rectangle(3.82,8.65); System.out.println("가로:3.82, 세로: 8.65"); System.out.println("면적 : "+rc.getArea()); System.out.println("둘레 : "+rc.getCircumference()); } } 10 - package Computer; class Computer{ public static final String[] osType = {"윈도우7","애플 OS X","안드로이드"}; private int OS; // 배열의 인덱스 i 역할을 할 것임 int Memory = 8; Computer(int OS,int Memory){ this.OS = OS; this.Memory = Memory; } void show() { System.out.printf("운영체제: %s, 메인메모리: %d %n", osType[OS], Memory); } } public class Main { public static void main(String[] args) { Computer pc = new Computer(0,16); Computer apple = new Computer(1,32); Computer Android = new Computer(2, 16); pc.show(); apple.show(); Android.show(); } } 반응형 [22] 클래스를 활용한 연습 문제 문제) 전화번호부를 관리하는 프로그램을 만들어보자. – public class PhoneInfo 소스 코드 (class) package kosta.phone; public class PhoneInfo { // 전화번호부 관리프로그램 구현하자 (1명의 전화번호부 ) // 상태 : 이름, 전화번호, 생년월일 // 기능 : 1명의 전화내역을 출력 // 1. 각각의 상태에 따른 필드(속성)을 선언한다. String name; // 이름 String phoneNo; // 전화번호 String birth; // 생년월일 // 2. 사용할 생성자를 생성한다. (생성자는 리턴형이 존재하지 않는다.) public PhoneInfo() {} // 디폴트 생성자(기본 생성자) : 입력매개변수(파라미터)가 아무것도 없을 때를 항상 생각한다. // 3. Source 메뉴에서 필드를 통해서 만들어준다. (직접 입력도 가능하다.) public PhoneInfo(String name, String phoneNo, String birth) { super(); this.name = name; this.phoneNo = phoneNo; this.birth = birth; } // 4. 전화내역을 출력할 메서드를 생성한다. public void show() { // 출력은 리턴값이 필요하지 않기 때문에, void를 사용한다. -> void의 사용은 입력매개변수(파라미터)가 없음과도 같다. System.out.println(“이름 : “+name); System.out.println(“전화번호 : “+phoneNo); System.out.println(“생년월일 : “+birth); } // -> 상태와 기능을 구현했으면, maim() 영역으로 가자~ } – public class Manager 소스 코드 (class) package kosta.phone; import java.util.Scanner; public class Manager { Scanner sc = new Scanner(System.in); PhoneInfo[] arr = new PhoneInfo[10]; // PhoneInfo 클래스에 대한 10개의 객체를 만들었다. int count = 0; // 1. 프로그램을 구동할 세부적인 메서드(기능적인 부분)를 만들어준다. // 기능 : 전화번호 추가, 전화번호 출력, 전화번호 검색 public void addPhone() { System.out.print(“이름 : “); String name = sc.nextLine(); System.out.print(“전화번호 : “); String phoneNo = sc.nextLine(); System.out.print(“생년월일 : “); String birth = sc.nextLine(); arr[this.count++] = new PhoneInfo(name, phoneNo, birth); // 전화번호를 추가할 때마다 각각의 객체에 데이터를 추가한다. System.out.println(“전화번호가 등록되었습니다.”); } // 전화번호 추가 public void listPhone() { for (int i = 0; i < this.count; i++) { arr[i].show(); // PhoneInfo 클래스에 대한 show() 메서드를 호출 } } // 전화번호 출력 public void searchPhone() { System.out.print("이름 : "); String name = sc.nextLine(); // 찾고자하는 변수를 만들고, 입력한다. int idx = -1; // 문자열의 위치를 알기 위해서 만든 변수이다. // name 내가 쓴 문자열이 어디 있는지 모르기 때문에 하나씩 비교한다. for문으로.. for(int i = 0; i < count; i++) { PhoneInfo info = arr[i]; // 이미 생성된 객체를 변수에 넣는 것이므로, new 연산자를 사용하지 않아도 된다. if(name.equals(info.name)) { // i값은 배열의 위치를 알려준다. info.show(); idx = i; // 문자열의 존재여부를 확인 - 임시 변수! (0~9) break; // 나간다! } } if (idx == -1) { System.out.println("해당하는 정보를 찾을 수 없습니다."); } } // 전화번호 검색 //////////////////////////////////////////////////////////////////////////// // <<<<<<<<<<<<<<<<<<<<<<<<< Main() 영역 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // // 2. Manager 클래스를 Main() 영역에서 사용하기 위한 객체를 생성한다. // // < 객체를 반복적으로 생성하면 값에 영향을 주므로, Scanner 밑에 생성하는 것이 좋다. > // Manager m = new Manager(); // // // 3. 생성한 Manager 클래스에 대한 객체의 메서드(기능적인 부분)을 뼈대에 추가한다. // m.addPhone(); // m.listPhone(); // m.searchPhone(); //////////////////////////////////////////////////////////////////////////// // 4. 매서드를 하나씩 구현하기 위한 코드를 작성한다. // addPhone() {소스 코드 작성}, listPhone() {소스 코드 작성}, searchPhone() {소스 코드 작성} // 5. 전화번호의 추가와 검색에 필요한 자바 입력 API Scanner을 만든다. // Scanner sc = new Scanner(System.in); // 6. 전화번호부 관리프로그램의 상태와 기능을 담당하는 PhoneInfo 클래스의 객체를 생성한다. // PhoneInfo[] arr = new PhoneInfo[10]; // // 7.1 전화번호를 추가하는 메서드인 addPhone() {}의 소스 코드를 작성한다. // 모든 변수의 쓰임은 항상 통일해주는 것이 좋다. // String name = sc.nextLine();, String phoneNo = sc.nextLine();, String birth = sc.nextLine(); // 7.2 전화번호를 관리하는 arr[] 배열의 인덱스를 바꿔줄 수 있는 count를 선언한다. // int count = 0; // arr[count++] = new PhoneInfo(name, phoneNo, birth); // // 8. 전화번호부를 잔체출력하는 메서드인 listPhone() {}의 소스 코드를 작성한다. // for문을 사용하여, arr[]의 인덱스를 count의 멤버변수(필드)에 저장된 값에 따라서 결과를 출력한다. // 출력을 할때는, PhoneInfo 클래스의 show() 메서드를 사용한다. // <<<<<<<<<<<<< 향상된 for문을 사용하면 안된다. 각각의 인덱스에 접근할 수 없기 때문이다. >>>>>>>>>>> // 9. 전화번호부를 검색하는 메서드인 searchPhone() {}의 소스 코드를 작성한다. // idx = -1; 배열은 0부터 시작하므로, -1로 초기화한 변수를 하나 선언한다. // 이름에 대한 문자열을 비교하기 위해서, 각각의 객체의 값들을 info 변수에 넣어준다. PhoneInfo info = arr[i]; // equals 자바 APT를 통하여, if(name.equals(info.name))로 이름 문자열을 비교한다. // 있을 경우, PhoneInfo 클래스의 show 메서드로 info의 변수에 존재하는 대한 arr[idx]에 대한 데이터를 출력한다. // 없는 경우, idx의 초기값인 -1을 그대로 얻으므로써 없다라는 메세지를 출력한다. // -> 세부적인 기능을 구현했으면, 실행한다. } – public class Main 소스 코드 (Main) package kosta.phone; import java.util.Scanner; public class Main { public static void main(String[] args) { // 1. 자바 입력 API Scanner을 만든다. Scanner sc = new Scanner(System.in); Manager m = new Manager(); // Manager 클래스에 대한 객체를 하나 생성한다. // 2. 구현할 시스템의 뼈대를 만든다. // -> 뼈대 : 눈에 보이는 글씨와 사용자가 직접 입력하는 값 while (true) { System.out.println(“1.추가 2.전체 출력 3.검색 4.종료”); System.out.print(“메뉴의 번호 선택 : “); String menu = sc.nextLine(); // String 데이터형으로 받으면, 문자열을 선택하는 조건이 있어야한다. switch (menu) { // switch (menu) 입력되는 값에 따라서, case를 찾아간다. case “1”: // 1.추가 m.addPhone(); break; case “2”: // 2.전체출력 m.listPhone(); break; case “3”: // 3.검색 m.searchPhone(); break; case “4”: // 4.종료 System.out.println(“프로그램이 종료되었습니다.”); return; // 값을 반환하지 않으면, 종료의 역할을 수행한다. } } // -> 뼈대(눈에 보이는 글씨와 사용자가 직접 입력하는 값)를 구현했으면, Manager() 영역으로 가자~ } }

04장 연습문제

(연습문제 풀이 : https://wikidocs.net/157712#04) Q1 다음 코드의 출력 결과는 무엇일까? (눈으로 해석하고 풀어보자.) public class Sample { public static void main(String[] args) { String a = “write once, run anywhere”; if (a.contains(“wife”)) { System.out.println(“wife”); } else if (a.contains(“once”) && !a.contains(“run”)) { System.out.println(“once”); } else if (!a.contains(“everywhere”)) { System.out.println(“everywhere”); } else if (a.contains(“anywhere”)) { System.out.println(“anywhere”); } else { System.out.println(“none”); } } } Q2 while문을 사용해 1부터 1000까지의 자연수 중 3의 배수의 합을 구해 보자. Q3 while문 또는 for 문을 사용하여 다음과 같이 별( * )을 표시하는 프로그램을 작성해 보자. * ** *** **** ***** Q4 for문을 사용해 1부터 100까지의 숫자를 출력해 보자. Q5 A 학급에 총 10명의 학생이 있다. 이 학생들의 중간고사 점수는 다음과 같다. int[] marks = {70, 60, 55, 75, 95, 90, 80, 80, 85, 100}; for each 문을 사용하여 A 학급의 평균 점수를 구해 보자.

Java 기초 클래스 – 연습문제(2)

글 작성자: 취업중인 피터팬 기본 환경 JDK : 1.8.0_261 버전 JRE : 1.8.0_261 버전 JAVA VERSION : 8 업데이트 261 Eclipse IDE VERSION : 2020-06버전 시나리오 Triangle 클래스을 만들어 밑변과 높이를 전달해 주고 삼격형의 높이를 구하는 클래스를 만들어라 다음과 같은 결과가 나와야 합니다. public class QuTriangle { public static void main(String[] args) { Triangle t = new Triangle(); t.init(10, 17); //밑변10, 높이17로 초기화 System.out.println(“삼각형의 넓이 : ” + t.getArea()); t.setBottom(50);//밑변 50으로 변경 t.setHeight(14);//높이 14로 변경 System.out.println(“삼각형의 넓이 : ” + t.getArea()); } } 정답 package ex08Class; class Triangle{ //맴버 변수 double Bottom; double Height; //밑변과 높이를 초기화 하는 맴버메소드 void init(double bottom, double height) { this.Bottom = bottom; this.Height = height; } //삼각형의 넓이를 구하는 맴버메소드 double getArea() { double result = (Bottom * Height) / 2.0; return result; } //밑변을 설정 void setBottom(double bottom) { this.Bottom = bottom; } //높이를 설정 void setHeight(double height) { this.Height = height; } } public class QuTriangle { public static void main(String[] args) { Triangle t = new Triangle(); t.init(10, 17); //밑변10, 높이17로 초기화 System.out.println(“삼각형의 넓이 : ” + t.getArea()); t.setBottom(50);//밑변 50으로 변경 t.setHeight(14);//높이 14로 변경 System.out.println(“삼각형의 넓이 : ” + t.getArea()); } } 사실 생성자를 써야 하지만 init()함수로 초기화 해주었습니다. 생성자를 사용하는 것이 더 좋은 코드입니다. 728×90

[명품 JAVA] 4장 실습문제 (클래스와 객체)

반응형 [공지] 코딩, 솔루션, 포스팅 주제 관련 [4장 1번] 자바 클래스를 작성하는 연습을 해보자. 다음 main() 메소드를 실행하였을 때 예시와 같이 출력되도록 TV 클래스를 작성하라. public static void main( String [] args) { TV myTV = new TV( “LG” , 2017 , 32 ); //LG에서 만든 2017년 32인치 myTV.show(); } LG에서 만든 2017년형 32인치 TV [풀이] package java_study4_1; class TV { private String brand; private int year; private int inch; TV( String brand, int year, int inch) { this .brand = brand; this .year = year; this .inch = inch; } public void show() { System.out.println(brand+ “에서 만든 ” +year+ “년형 ” +inch+ “인치 TV” ); } } public class java_study4_1 { public static void main( String [] args) { // TODO Auto-generated method stub TV myTV = new TV( “LG” , 2017 , 32 ); myTV.show(); } } [4장 2번] Grade 클래스를 작성해보자. 3 과목의 점수를 입력받아 Grade 객체를 생성하고 성적 평균을 출력하는 main()과 실행 예시는 다음과 같다. public static void main( String [] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System. in ); System.out.print( “수학, 과학, 영어 순으로 3개의 정수 입력 >> ” ); int math = sc.nextInt(); int science = sc.nextInt(); int english = sc.nextInt(); Grade me = new Grade(math, science, english); System.out.println( “평균은 ” +me.average()); // average()는 평균을 계산하여 리턴 sc.close(); } 수학, 과학, 영어 순으로 3개의 정수 입력 >> 90 88 96 평균은 91 [Hint] Grade 클래스에 int 타입의 math, science, english 필드를 private로 선언하고, 생성자와 세 과목의 평균을 리턴하는 average() 메소드를 작성한다. [풀이] package java_study4_2; import java.util.Scanner; class Grade { private int math; private int science; private int english; Grade(int math, int science, int english) { this .math = math; this .science = science; this .english = english; } public int average() { return (math + science + english) / 3 ; } } public class java_study4_2 { public static void main( String [] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System. in ); System.out.print( “수학, 과학, 영어 순으로 3개의 정수 입력 >> ” ); int math = sc.nextInt(); int science = sc.nextInt(); int english = sc.nextInt(); Grade me = new Grade(math, science, english); System.out.println( “평균은 ” +me.average()); sc.close(); } } [4장 3번] 노래 한 곡을 나타내는 Song 클래스를 작성하라. Song은 다음 필드로 구성된다. – 노래의 제목을 나타내는 title – 가수를 나타내는 artist – 노래가 발표된 연도를 나타내는 year – 국적을 나타내는 country 또한 Song 클래스에 다음 생성자와 메소드를 작성하라. – 생성자 2개: 기본 생성자와 매개변수로 모든 필드를 초기화하는 생성자 – 노래 정보를 출력하는 show() 메소드 – main() 메소드에서는 1978년, 스웨덴 국적의 ABBA가 부른 “Dancing Queen”을 song 객체로 생성하고 show()를 이용하여 노래의 정보를 다음과 같이 출력하라. 1978년 스웨덴국적의 ABBA가 부른 Dancing Queen [풀이] package java_study4_3; class Song { private String title; private String artist; private int year; private String country; Song() { this ( “title” , “artist” , 0000 , “country” ); } Song( String title, String artist, int year, String country) { this .title = title; this .artist = artist; this .year = year; this .country = country; } public void show() { System.out.println(year+ “년 ” +country+ “국적의 ” +artist+ “가 부른 ” +title); } } public class java_study4_3 { public static void main( String [] args) { // TODO Auto-generated method stub Song song = new Song( “Dancing Queen” , “ABBA” , 1978 , “스웨덴” ); song.show(); } } [4장 4번] 다음 멤버를 가지고 직사각형을 표현하는 Rectangle 클래스를 작성하라. – int 타입의 x, y, width, height 필드: 사각형을 구성하는 점과 크기 정보 – x, y, width, height 값을 매개변수로 받아 필드를 초기화하는 생성자 – int square() : 사각형 넓이 리턴 – void show() : 사각형의 좌표와 넓이를 화면에 출력 – boolean contatins(Rectangle r) : 매개변수로 받은 r이 현 사각형 안에 있으면 true 리턴 – main() 메소드의 코드와 실행 결과는 다음과 같다 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를 포함합니다.” ); } (2,2)에서 크기가 8×7인 사각형 s의 면적은 36 t는 r을 포함합니다. [풀이] package java_study4_4; class Rectangle { private int x; private int y; private int width; private int height; Rectangle(int x, int y, int width, int height) { this .x = x; this .y = y; this .width = width; this .height = height; } public void show() { System.out.println( “(” +x+ “,” +y+ “)에서 크기가 ” +width+ “x” +height+ “인 사각형” ); } public int square() { return (width*height); } boolean contains(Rectangle r) { if (x < r.x && y < r.y) if ((width+x) > (r.x+r.width) && (height+y) > (r.y+r.height)) return true ; return false ; } } public class java_study4_4 { public static void main( String [] args) { // TODO Auto-generated method stub 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를 포함합니다.” ); } } [4장 5번] 다음 설명대로 Circle 클래스와 CircleManager 클래스를 완성하라. import java.util.Scanner; class Circle { private double x, y; private int radius; public Circle(double x, double y, int radius) { _______________________________; //x, y, radius 초기화 } public void show() { _______________________________ } } public class CircleManager { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = ___________________; Circle c[] = ______________; // 3개의 Circle 배열 선언 for(int i=0; i < _______; i ++) { System.out.print("x, y, radius >>”); ______________________; // x값 읽기. ______________________; // y값 읽기. _______________________; // radius값 읽기. c[i] = ____________________; // Circle 객체 생성 } for(int i=0; i >3.0 3.0 5 x, y, radius >>2.5 2.7 6 x, y, radius >>5.0 2.0 4 (3.0,3.0)5 (2.5,2.7)6 (5.0,2.0)4 [풀이] package java_study4_5; 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, y, radius 초기화 this .y =y; this .radius = radius; } public void show() { System.out.println( “(” + x + “,” + y + “)” + radius); } } public class CircleManager { public static void main( String [] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System. in ); Circle c[] = new Circle[ 3 ]; // 3개의 Circle 배열 선언 for (int i= 0 ; i < c.length; i ++) { System.out.print( "x, y, radius >>” ); double x = sc.nextDouble(); // x값 읽기. double y = sc.nextDouble(); // y값 읽기. int radius = sc.nextInt(); // radius값 읽기. c[i] = new Circle(x, y, radius); // Circle 객체 생성 } for (int i= 0 ; i >3.0 3.0 5 x, y, radius >>2.5 2.7 6 x, y, radius >>5.0 2.0 4 가장 면적인 큰 원은 (2.5,2.7)6 [풀이] package java_study4_6; 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, y, radius 초기화 this .y =y; this .radius = radius; } public void show() { System.out.println( “(” + x + “,” + y + “)” + radius); } public int getRadius() { return radius; } } public class CircleManager { public static void main( String [] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System. in ); Circle c[] = new Circle[ 3 ]; // 3개의 Circle 배열 선언 int max= 0 ; for (int i= 0 ; i < c.length; i ++) { System.out.print( "x, y, radius >>” ); double x = sc.nextDouble(); // x값 읽기. double y = sc.nextDouble(); // y값 읽기. int radius = sc.nextInt(); // radius값 읽기. c[i] = new Circle(x, y, radius); // Circle 객체 생성 } for (int i= 0 ; i >1 날짜(1~30)?1 할일(빈칸없이입력)?자바공부 할일(입력:1, 보기:2, 끝내기:3) >>2 날짜(1~30)?1 1일의 할 일은 자바공부입니다. 할일(입력:1, 보기:2, 끝내기:3) >>3 프로그램을 종료합니다. [Hint] MonthSchedule에는 생성자, input(), view(), finish(), run() 메소드를 만들고 main()에서 다음과 같이 호출하여 실행하고 run()에서 메뉴를 출력하고 처리한다. MonthSchedule april = new MonthSchedule( 30 ); // 4월달의 할 일 april.run(); [풀이] package java_study4_7; import java.util.Scanner; class Day { private String work; // 하루의 할 일을 나타내는 문자열 public void set( String work) { this .work = work; } public String get() { return work; } public void show() { if (work == null ) System.out.println( “없습니다.” ); else System.out.println(work + “입니다.” ); } } public class MonthSchedule { private Scanner sc; private Day days[]; MonthSchedule(int day) { this .days = new Day[day]; for (int i= 0 ; i 30 ) { // 0~29 System.out.println( “날짜를 잘못 입력하였습니다.” ); return ; } days[day].set(work); } private void view() { System.out.print( “날짜(1~30)?” ); int day = sc.nextInt(); day–; if (day < 0 || day > 30 ) { // 0~29 System.out.println( “날짜를 잘못 입력하였습니다.” ); return ; } System.out.print((day+ 1 )+ “일의 할 일은 ” ); days[day].show(); } private void finish() { System.out.println( “프로그램을 종료합니다.” ); sc.close(); } public void run() { System.out.print( “이번달 스케쥴 관리 프로그램.” ); while ( true ) { System.out.println(); System.out.print( “할일(입력:1, 보기:2, 끝내기:3) >>” ); int select = sc.nextInt(); switch(select) { case 1 : input(); break ; case 2 : view(); break ; case 3 : finish(); return ; } } } public static void main( String [] args) { // TODO Auto-generated method stub MonthSchedule april = new MonthSchedule( 30 ); // 4월달의 할 일 april.run(); } } [4장 8번] 이름(name), 전화번호(tel) 필드와 생성자 등을 가진 Phone 클래스를 작성하고, 실행 예시와 같이 작동하는 PhonBook 클래스를 작성하라. 인원수 >> 3 이름과 전화번호(이름과 번호는 빈 칸없이 입력)>>황기태 777-7777 이름과 전화번호(이름과 번호는 빈 칸없이 입력)>>나명품 999-9999 이름과 전화번호(이름과 번호는 빈 칸없이 입력)>>최자바 333-1234 저장되었습니다… 검색할 이름 >>황기순 황기순이 없습니다. 검색할 이름 >>최자바 최자바의 번호는 333-1234 입니다. 검색할 이름 >>그만 [Hint] PhoneBook 클래스에서 저장할 사람의 수를 입력받고, Phone 개게 배열을 생성한다. 한 사람의 정보는 하나의 Phone 객체에 저장한다. 7번 정답을 참고하기 바란다. 문자열 a와 b가 같은지 비교할 때 a.equals(b)가 참인지로 판단한다. [풀이] package java_study4_8; import java.util.Scanner; class Phone { private String name; private String tel; Phone( String name, String tel) { this .name = name; this .tel = tel; } public String getName() { return name; } public String getTel() { return tel; } } public class PhoneBook { public static void main( String [] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System. in ); Phone phone[]; int i; System.out.print( “인원수 >> ” ); int num = sc.nextInt(); phone = new Phone[num]; for (i= 0 ; i >” ); String name = sc.next(); String tel = sc.next(); phone[i] = new Phone(name, tel); } System.out.println( “저장되었습니다…” ); while ( true ) { System.out.print( “검색할 이름 >>” ); String name = sc.next(); for (i= 0 ; i > 5 7 * 35 [풀이] package java_study4_11; import java.util.Scanner; class Add { private int a; private int b; public void setValue(int a, int b) { this .a = a; this .b = b; } public int calculate() { return a+b; } } class Sub { private int a; private int b; public void setValue(int a, int b) { this .a = a; this .b = b; } public int calculate() { return a-b; } } class Mul { private int a; private int b; public void setValue(int a, int b) { this .a = a; this .b = b; } public int calculate() { return a*b; } } class Div { private int a; private int b; public void setValue(int a, int b) { this .a = a; this .b = b; } public int calculate() { return a/b; } } public class java_study4_11 { public static void main( String [] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System. in ); int result= 0 ; System.out.print( “두 정수와 연산자를 입력하시오 >> ” ); int a = sc.nextInt(); int b = sc.nextInt(); char c = sc.next().charAt( 0 ); switch(c) { case ‘+’ : Add add = new Add(); add.setValue(a, b); result = add.calculate(); break ; case ‘-‘ : Sub sub = new Sub(); sub.setValue(a, b); result = sub.calculate(); break ; case ‘*’ : Mul mul = new Mul(); mul.setValue(a, b); result = mul.calculate(); break ; case ‘/’ : Div div = new Div(); div.setValue(a, b); result = div.calculate(); break ; } System.out.println(result); sc.close(); } } [4장 12번] 간단한 콘서트 예약 시스템을 만들어보자. 다수의 클래스를 다루고 객체의 배열을 다루기에는 아직 자바 프로그램 개발이 익숙하지 않은 초보자에게 다소 무리가 있을 것이다. 그러나 반드시 넘어야 할 산이다. 이 도전을 통해 산을 넘어갈 수 있는 체력을 키워보자. 예약 시스템의 기능은 다음과 같다. – 공연은 하루에 한 번 있다. – 좌석은 S석, A석, B석으로 나뉘며, 각각 10개의 좌석이 있다. – 예약 시스템의 메뉴는 “예약”, “조회”, “취소”, “끝내기”가 있다. – 예약은 한 자리만 가능하고, 좌석 타입, 예약자 이름, 좌석 번호를 순서대로 입력받아 예약한다. – 조회는 모든 좌석을 출력한다. – 취소는 예약자의 이름을 입력받아 취소한다. – 없는 이름, 없는 번호, 없는 메뉴, 잘못된 취소 등에 대해서 오류 메시지를 출력하고 사용자가 다시 시도하도록 한다. 명품콘서트홀 예약 시스템입니다. 예약:1, 조회:2, 취소:3, 끝내기:4 >> 1 좌석구분 S(1), A(2), B(3)>>1 S>> ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ 이름>>황기태 번호>>1 예약:1, 조회:2, 취소:3, 끝내기:4 >> 1 좌석구분 S(1), A(2), B(3)>>2 A>> ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ 이름>>김효수 번호>>5 예약:1, 조회:2, 취소:3, 끝내기:4 >> 2 S>> 황기태 ___ ___ ___ ___ ___ ___ ___ ___ ___ A>> ___ ___ ___ ___ 김효수 ___ ___ ___ ___ ___ B>> ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ <<>> 예약:1, 조회:2, 취소:3, 끝내기:4 >> 3 좌석 S:1, A:2, B:3>>2 A>> ___ ___ ___ ___ 김효수 ___ ___ ___ ___ ___ 이름>>김효수 예약:1, 조회:2, 취소:3, 끝내기:4 >> 2 S>> 황기태 ___ ___ ___ ___ ___ ___ ___ ___ ___ A>> ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ B>> ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ <<>> 예약:1, 조회:2, 취소:3, 끝내기:4 >> 4 [풀이] package java_study4_12; import java.util.Scanner; class Concert{ private String S[]; private String A[]; private String B[]; private Scanner sc; Concert() { sc = new Scanner(System. in ); S = new String [ 10 ]; A = new String [ 10 ]; B = new String [ 10 ]; for (int i= 0 ; i >” ); Concert.printSeat(S); System.out.print( “A>>” ); Concert.printSeat(A); System.out.print( “B>>” ); Concert.printSeat(B); System.out.println( “<<>>” ); } public void choiceSeat() { //좌석 선택(S, A, B) 메소드 while ( true ) { System.out.print( “좌석구분 S(1), A(2), B(3)>>” ); int select = sc.nextInt(); switch(select) { case 1 : System.out.print( “S>>” ); printSeat(S); inputSeat(S); return ; case 2 : System.out.print( “A>>” ); printSeat(A); inputSeat(A); return ; case 3 : System.out.print( “B>>” ); printSeat(B); inputSeat(B); return ; default: System.out.println( “다시 입력해 주세요.” ); } } } public void inputSeat( String seat[]) { //좌석에 이름값 넣는 메소드 System.out.print( “이름>>” ); String name = sc.next(); while ( true ) { System.out.print( “번호>>” ); int num = sc.nextInt(); num–; if (seat[num].equals( “___” )) { seat[num] = name; break ; } else { System.out.println( “다른 좌석을 선택해 주세요.” ); } } } public void d_choiceSeat() { while ( true ) { System.out.print( “좌석 S:1, A:2, B:3>>” ); int select = sc.nextInt(); switch(select) { case 1 : System.out.print( “S>>” ); printSeat(S); delete (S); return ; case 2 : System.out.print( “A>>” ); printSeat(A); delete (A); return ; case 3 : System.out.print( “B>>” ); printSeat(B); delete (B); return ; default: System.out.println( “다시 입력해 주세요.” ); } } } public void delete ( String seat[]) { System.out.print( “이름>>” ); String name = sc.next(); for (int i= 0 ; i > ” ); int select = sc.nextInt(); switch(select) { case 1 : concert.choiceSeat(); break ; case 2 : concert.allPrint(); break ; case 3 : concert.d_choiceSeat(); break ; case 4 : sc.close(); return ; default : System.out.println( “다시 입력해 주세요.” ); } } } } 반응형

JAVA1_day15 | 클래스 Class 연습문제 (1)

문제3. “인스턴스 메서드 입니다.” 라는 출력문을 보여주는 클래스 showInfo() 문제4. 정수 2개를 전달받아(인자,argument) 두 수를 더한 결과를 return해주는 클래스 sum() 문제5. 이름(문자) 1개를 전달받아 “나는 이름 입니다.” 라는 출력문을 보여주는 인스턴스 showName() 문제6. 세 개의 정수를 전달받아, 최대값과 최소값을 구하는 메서드를 만들어보자. 문제7. 국어, 영어, 수학 3과목의 점수를 입력받아, 총점과 평균을 구하는 메서드를 만들어보자. “국어, 영어, 수학의 점수를 입력해주세요: ” System . out . print ( “국어, 영어, 수학의 점수를 입력해주세요: ” ); 문제8. char[] 배열을 전달받아 출력하는 printWord() 메서드와 배열 속의 공백(‘ ‘) 문자를 ‘,’ 로 대체하는 replace()메서드를 작성해보자. // 문자형 배열은 바로 그 값을 나타낸다. // 문자형 배열은 바로 그 값을 나타낸다. # 설명 Line 37: Scanner를 이용하여 입력받은 문자열 str의 길이만큼 문자형 배열 char[] arr를 생성해준다. Line 38~41: arr의 길이만큼 for문을 돌아 charAt(index)를 통하여 입력받은 문자열 하나씩 arr 배열에 입력해준다. Line 9: 정수형 배열과는 다르게 문자형 배열은 변수값인 arr를 그대로 출력할 경우 주소값이 아닌 데이터값이 그대로 출력된다. 그러나 문자열 다음에 출력하게 되면 그때는 주소값이 나온다. Line 12~17: 인자로 받은 arr의 길이만큼 for문을 돌며 arr의 값이 공백일 경우 즉, arr[i] == ‘ ‘ 일 때 그 값을 , 로 변경해준다.

자바 4장 연습문제(클래스와 객체)-2

728×90 2021/03/14(일) ​ ​ ​ ​ ​ 문제) — 내풀이는 밑에 4-5) 다음 설명대로 Circle 클래스와 CircleManager 클래스를 완성하라. import java.util.Scanner; class Circle{ private double x, y; private int radius; public Circle(double x, double y, int radius) { } public void show() { } } public class CircleManager { public static void main(String[] args) { Scanner scanner = Circle c[] = for(int i=0; i< ; i++) { System.out.print("x, y, radius >>”); // x값이 읽기 // y값이 읽기 // 반지름 읽기 c[i] = } for(int i=0; i > 3.0 3.0 5 x, y, radius >> 2.5 2.7 6 x, y, radius >> 5.0 2.0 4 (3.0,3.0)5 (2.5,2.7)6 (5.0,2.0)4 ​ ​ ​ 4-6) 앞의 5번 문제는 정답이 공개되어 있다. 이 정답을 참고하여 Circle 클래스와 CircleManager 클래스를 수정하여 다음 실행 결과처럼 되게 하라. x, y, radius >> 3.0 3.0 5 x, y, radius >> 2.5 2.7 6 x, y, radius >> 5.0 2.0 4 가장 면적이 큰 원은 (2.5,2.7)6 ​ ​ ​ ​ ​ 4-7) 하루의 할 일을 표현하는 클래스 Day는 다음과 같다. 한 달의 할 일을 표현하는 MonthSchedule 클래스를 작성하라. class Day{ private String work; public void set(String work) { this.work = work; } public String get() { return work; } public void show() { if(work == null)System.out.println(“없습니다.”); else System.out.println(work+”입니다.”); } } MonthSchedule 클래스에는 Day 객체 배열과 적절한 필드, 메소드를 작성하고 실행 예시처럼 입력, 보기, 끝내기 등의 3개의 기능을 작성하라. 이번달 스케쥴 관리 프로그램. 할일(입력:1, 보기:2, 끝내기:3) >> 1 날짜(1~30)? 1 할일(빈칸없이입력)> 자바공부 할일(입력:1, 보기:2, 끝내기:3) >> 2 날짜(1~30)? 1 1일의 할 일은 자바공부입니다. 할일(입력:1, 보기:2, 끝내기:3) >> 3 프로그램을 종료합니다. ​ ​ ​ ​ ​ 4-8) 이름(name), 전화번호(tel) 필드와 생성자 등을 가진 Phone 클래스를 작성하고, 실행 예시와 같이 작동하는 PhoneBook 클래스를 작성하라. 인원수 >> 3 이름과 전화번호(이름과 번호는 빈 칸없이 입력)>> 황기태 777-7777 이름과 전화번호(이름과 번호는 빈 칸없이 입력)>> 나명품 999-9999 이름과 전화번호(이름과 번호는 빈 칸없이 입력)>> 최자바 333-1234 저장되었습니다… 검색할 이름>> 황기순 황기순이 없습니다. 검색할 이름>> 최자바 최자바의 번호는 333-1234 입니다. 검색할 이름>> 그만 ​ ​ ​ ​ ​ ​ ​ ​ ​ 내 풀이 4-5) import java.util.Scanner; class Circle{ private double x, y; private int radius; public Circle(double x, double y, int radius) { this.x = x; this.y = y; this.radius = radius; } public void show() { System.out.println(“(“+x+”,”+y+”)”+radius); } } public class CircleManager { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Circle c[] = new Circle[3]; for(int i=0; i >”); double x = scanner.nextDouble(); double y = scanner.nextDouble(); int radius = scanner.nextInt(); c[i] = new Circle(x, y, radius); } for(int i=0; i >”); double x = scanner.nextDouble(); double y = scanner.nextDouble(); int radius = scanner.nextInt(); c[i] = new Circle(x, y, radius); //가장 큰 반지름을 max에 저장 if(max >”); int selectNumber = scan.nextInt(); if(selectNumber ==1) { System.out.print(“날짜(1~30)?”); int date = scan.nextInt(); input(date); System.out.println(); } else if(selectNumber==2) { System.out.print(“날짜(1~30)?”); int date = scan.nextInt(); view(date); System.out.println(); } else { finish(); } } } public static void main(String[] args) { MonthSchedule april = new MonthSchedule(30); april.run(); } } ​ ​ ​ ​ 4-8) import java.util.Scanner; class Phone{ private String name; private String phone; public Phone(String name, String phone) { this.name = name; this.phone = phone; } public String getName() { return name; } public String getPhone() { return phone; } } public class PhoneBook { Scanner scan = new Scanner(System.in); Phone[] phone = null; public void run() { System.out.print(“인원수>>”); int howManyPerson = scan.nextInt(); phone = new Phone[howManyPerson]; insert(); search(); } //인원수에 따라 이름과 전화번호 입력받는 메소드 public void insert() { for(int i=0; i >”); String name = scan.next(); String phoneNumber = scan.next(); phone[i] = new Phone(name, phoneNumber); if(i==phone.length-1) System.out.println(“저장되었습니다.”); } } //이름을 검색하는 메소드 public void search() { while(true) { System.out.print(“검색할 이름>>”); String searchName = scan.next(); //입력받은 이름으로 배열검색 for(int i=0; i

[Java] 연습문제

연습문제 Q6) 카드 회사에서 카드를 발급할 때마다 카드 고유 번호를 부여해 준다. 06-3의 예제를 참고하여 카드가 생성될 때마다 카드 번호가 자동으로 증가할 수 있도록 카드 클래스를 만들고 생성해보자. ​ ​ package singleton; public class Card { private static int serialNum = 100; String cardName; int cardNum; public Card() { serialNum++; cardNum = serialNum; } public Card(String card) { serialNum++; cardNum = serialNum; this.cardName = card; } public int getCardNum() { return cardNum; } } package singleton; public class CardTest { public static void main(String[] args) { Card card1 = new Card(); Card card2 = new Card(); Card card3 = new Card(“BC”); System.out.println(card1.cardName + ” 카드번호 : ” + card1.getCardNum()); System.out.println(card2.cardName + ” 카드번호 : ” + card2.getCardNum()); System.out.println(card3.cardName + ” 카드번호 : ” + card3.getCardNum()); } } 더보기 ​ package singleton; public class Card { private static int serialNum = 100; String cardName; String cardNum; public Card() { serialNum++; cardNum = String.valueOf(serialNum); } public Card(String cardName) { this(); this.cardName = cardName; } public String getCardNum() { return cardNum; } } package singleton; public class CardTest { public static void main(String[] args) { Card card1 = new Card(); Card card2 = new Card(); Card card3 = new Card(“BC”); System.out.println(card1.cardName + ” 카드번호 : ” + card1.getCardNum()); System.out.println(card2.cardName + ” 카드번호 : ” + card2.getCardNum()); System.out.println(card3.cardName + ” 카드번호 : ” + card3.getCardNum()); } } 연습문제 Q7) Q6에 구현한 내용에 카드 회사 클래스 CardCompany를 싱글톤 패턴을 사용하여 구현해 보라. package singleton; public class CardCompany { private static CardCompany instance; private CardCompany() { } public static CardCompany getInstance() { if (instance == null) { instance = new CardCompany(); } return instance; } public Card createCard() { return new Card(); } public Card createCard(String cardName) { return new Card(cardName); } } package singleton; public class CardCompanyTest { public static void main(String[] args) { CardCompany company = CardCompany.getInstance(); Company myBC = Company.createCard(); Company myVisa = Company.createCard(“Visa”); System.out.println(myBC.cardName + ” ” + myBC.getCardNum()); System.out.println(myVisa.cardName + ” ” + myVisa.getCardNum()); } } ​ 심화문제 ) member 객체 생성시 성(last name)과 이름을 매개 변수로 받고 memberID값에 lastname이 포함되게 자동 할당 – 매개 변수 값이 없으면 안된다! 클래스 : Member 멤버 변수 : memberID, memberName, lastName – get, set 함수 Member 클래스 MemberTest 클래스 -주목! 이라고 표시한 부분과 Member 클래스에 노란 형광펜부분을 잘 살펴보자. ​ ​ ​ 심화문제 ) site 클래스 멤버 변수 : siteCode, siteName 클래스 변수 : 1. siteCode 값을 자동 증가 할당하는 변수 2. 싱글톤을 위한 변수 싱글톤으로 객체가 생성되게 작성을 하고 객체 생성 시 site이름을 입력받아 저장할수있게 할 것! ​ Site 클래스 -빨간색 밑줄 친 부분이 헷갈렸다. SiteTest 클래스

It’s better than Sinder!

04:59 It’s better than Sinder! Are you looking for a men or a women? Men Women What’s your gender? Men Women Are you older than 18 years? Yes No Do you agree to use a condom when having sex with a partner you meet on our site? Yes No

키워드에 대한 정보 자바 클래스 문제

다음은 Bing에서 자바 클래스 문제 주제에 대한 검색 결과입니다. 필요한 경우 더 읽을 수 있습니다.

이 기사는 인터넷의 다양한 출처에서 편집되었습니다. 이 기사가 유용했기를 바랍니다. 이 기사가 유용하다고 생각되면 공유하십시오. 매우 감사합니다!

사람들이 주제에 대해 자주 검색하는 키워드 Java – 13. 클래스

생활코딩

자바

Java

Java #- #13. #클래스

YouTube에서 자바 클래스 문제 주제의 다른 동영상 보기

주제에 대한 기사를 시청해 주셔서 감사합니다 Java – 13. 클래스 | 자바 클래스 문제, 이 기사가 유용하다고 생각되면 공유하십시오, 매우 감사합니다.

[Java] 연습문제

연습문제 Q6) 카드 회사에서 카드를 발급할 때마다 카드 고유 번호를 부여해 준다.

06-3의 <학번 생성하기> 예제를 참고하여 카드가 생성될 때마다 카드 번호가 자동으로 증가할 수 있도록 카드 클래스를 만들고 생성해보자.

<내가 한 것>

package singleton; public class Card { private static int serialNum = 100; String cardName; int cardNum; public Card() { serialNum++; cardNum = serialNum; } public Card(String card) { serialNum++; cardNum = serialNum; this.cardName = card; } public int getCardNum() { return cardNum; } }

package singleton; public class CardTest { public static void main(String[] args) { Card card1 = new Card(); Card card2 = new Card(); Card card3 = new Card(“BC”); System.out.println(card1.cardName + ” 카드번호 : ” + card1.getCardNum()); System.out.println(card2.cardName + ” 카드번호 : ” + card2.getCardNum()); System.out.println(card3.cardName + ” 카드번호 : ” + card3.getCardNum()); } }

<헷갈렸던 것>

<결과값>

더보기 ​<선생님이 한 것> package singleton; public class Card { private static int serialNum = 100; String cardName; String cardNum; public Card() { serialNum++; cardNum = String.valueOf(serialNum); } public Card(String cardName) { this(); this.cardName = cardName; } public String getCardNum() { return cardNum; } } package singleton; public class CardTest { public static void main(String[] args) { Card card1 = new Card(); Card card2 = new Card(); Card card3 = new Card(“BC”); System.out.println(card1.cardName + ” 카드번호 : ” + card1.getCardNum()); System.out.println(card2.cardName + ” 카드번호 : ” + card2.getCardNum()); System.out.println(card3.cardName + ” 카드번호 : ” + card3.getCardNum()); } }

연습문제 Q7) Q6에 구현한 내용에 카드 회사 클래스 CardCompany를 싱글톤 패턴을 사용하여 구현해 보라.

package singleton; public class CardCompany { private static CardCompany instance; private CardCompany() { } public static CardCompany getInstance() { if (instance == null) { instance = new CardCompany(); } return instance; } public Card createCard() { return new Card(); } public Card createCard(String cardName) { return new Card(cardName); } }

package singleton; public class CardCompanyTest { public static void main(String[] args) { CardCompany company = CardCompany.getInstance(); Company myBC = Company.createCard(); Company myVisa = Company.createCard(“Visa”); System.out.println(myBC.cardName + ” ” + myBC.getCardNum()); System.out.println(myVisa.cardName + ” ” + myVisa.getCardNum()); } }

<결과값>

심화문제 ) member 객체 생성시 성(last name)과 이름을 매개 변수로 받고

memberID값에 lastname이 포함되게 자동 할당 – 매개 변수 값이 없으면 안된다!

클래스 : Member 멤버 변수 : memberID, memberName, lastName – get, set 함수

Member 클래스

MemberTest 클래스

-주목! 이라고 표시한 부분과 Member 클래스에 노란 형광펜부분을 잘 살펴보자.

심화문제 ) site 클래스

멤버 변수 : siteCode, siteName 클래스 변수 : 1. siteCode 값을 자동 증가 할당하는 변수 2. 싱글톤을 위한 변수 싱글톤으로 객체가 생성되게 작성을 하고 객체 생성 시 site이름을 입력받아 저장할수있게 할 것!

Site 클래스

-빨간색 밑줄 친 부분이 헷갈렸다.

SiteTest 클래스

Top 30 자바 클래스 문제 The 5 Correct Answer

Java – 13. 클래스

Java – 13. 클래스

티스토리

공지사항

블로그 메뉴

인기 글

최근 글

최근 댓글

태그

JAVA (자바) – 클래스 연습 문제 모음 – (1)

티스토리툴바

Read More

Q1

Q2

Q3

Q4

Q5

Read More

문제

문제) 전화번호부를 관리하는 프로그램을 만들어보자

– public class PhoneInfo 소스 코드 (class)

– public class Manager 소스 코드 (class)

– public class Main 소스 코드 (Main)

See also Top 20 버터 플라이 꽃 28112 People Liked This Answer

Read More

댓글

이 글 공유하기

다른 글

Java 기초 package(2)

Java 기초 클래스 – 연습문제(3)

Java 기초 클래스 – 연습문제(1)

Java 기초 class(6) – 과일장수

티스토리툴바

Read More

See also Top 45 수 2 문제 Top 52 Best Answers

태그

관련글

댓글14

공지사항

광고글 D

최근글

인기글

최근댓글

태그

전체 방문자

티스토리툴바

Read More

JAVA1_day15 클래스 Class 연습문제 (1)

티스토리툴바

Read More

명품 JAVA Programming – Chapter4 연습문제(1 2 3 4 5 6)

티스토리툴바

자바 4장 연습문제(클래스와 객체)-2

Article author: cordingdoah.tistory.com

Reviews from users: 22816 Ratings

Ratings Top rated: 4.6

Lowest rated: 1

Summary of article content: Articles about 자바 4장 연습문제(클래스와 객체)-2 문제) — 내풀이는 밑에. 4-5) 다음 설명대로 Circle 클래스와 CircleManager 클래스를 완성하라. import java.util.Scanner; Circle{ private … …

Most searched keywords: Whether you are looking for 자바 4장 연습문제(클래스와 객체)-2 문제) — 내풀이는 밑에. 4-5) 다음 설명대로 Circle 클래스와 CircleManager 클래스를 완성하라. import java.util.Scanner; Circle{ private … 2021/03/14(일) ​ ​ ​ ​ ​ 문제) — 내풀이는 밑에 4-5) 다음 설명대로 Circle 클래스와 CircleManager 클래스를 완성하라. import java.util.Scanner; class Circle{ private double x, y; private int rad..코딩 공부하는 블로그

Table of Contents:

자바 4장 연습문제(클래스와 객체)-2

Read More

[Java] 연습문제

Article author: poew.tistory.com

Reviews from users: 31949 Ratings

Ratings Top rated: 4.6

Lowest rated: 1

Summary of article content: Articles about [Java] 연습문제 06-3의 예제를 참고하여 카드가 생성될 때마다 카드 번호가 자동으로 증가할 수 있도록 카드 클래스를 만들고 생성해보자. ​. ​.

Most searched keywords: Whether you are looking for [Java] 연습문제 06-3의 예제를 참고하여 카드가 생성될 때마다 카드 번호가 자동으로 증가할 수 있도록 카드 클래스를 만들고 생성해보자. ​. ​. 예제를 참고하여 카드가 생성될 때마다 카드 번호가 자동으로 증가할 수 있도록 카드 클래스를 만들고..

Table of Contents:

관련글

댓글0

공지사항

최근댓글

태그

전체 방문자

티스토리툴바

[Java] 연습문제

Read More

(문제 풀이)자바, 클래스만들기 응용

Article author: longway.tistory.com

Reviews from users: 28471 Ratings

Ratings Top rated: 4.3

Lowest rated: 1

Summary of article content: Articles about (문제 풀이)자바, 클래스만들기 응용 (문제 풀이)자바, 클래스만들기 응용. 오래걸려도괜찮아 2021. 12. 17. 18:35. 중심을 표현하는 … int 타입의 radius 필드를 가진 Circle 클래스를 작성하고자 한다. …

Most searched keywords: Whether you are looking for (문제 풀이)자바, 클래스만들기 응용 (문제 풀이)자바, 클래스만들기 응용. 오래걸려도괜찮아 2021. 12. 17. 18:35. 중심을 표현하는 … int 타입의 radius 필드를 가진 Circle 클래스를 작성하고자 한다. 중심을 표현하는 int 타입의 x, y 필드와 반지름 값을 저장하는 int 타입의 radius 필드를 가진 Circle 클래스를 작성하고자 한다. 생성자는 x,y, radius값을 인자로 받아 필드를 초기화 하고 equals() 메소드는..느려도 괜찮아. 오래 걸려도 괜찮아.

Table of Contents:

(문제 풀이)자바, 클래스만들기 응용

Read More

See more articles in the same category here: toplist.future-user.com/blog.

JAVA (자바) – 클래스 연습 문제 모음 – (1)

반응형 JAVA (자바) – 클래스 연습 문제 모음 – (1) 문제 1 – 다음을 만족하는 Student 클래스를 작성하시오. · String형의 학과와 정수형의 학번을 필드로 선언 · Student 클래스의 main() 메소드에서 Student 객체를 생성하여 학과와 학번 필드에 적당한 값을 입력 후 출력 문제 – 2. 위에서 구현한 Student 클래스를 다음을 만족하도록 기능을 추가하여 작성하시오. · 필드를 모두 private로 하고, getter와 setter를 구현하고 · Student 클래스의 main() 메소드에서 Student 객체를 생성하여 setter를 사용하여 학과와 학번 필드에 적당한 값을 입력 후 출력 문제 – 3. 다음에 구현된 Circle 클래스를 참고로 다음을 만족하는 Cylinder 클래스를 작성하시오. · 원통을 나타내는 Cylinder 클래스는 Circle형의 원과 실수형의 높이를 필드로 선언 · 메소드 getVolume()은 원통의 부피를 반환 · Cylinder 클래스의 main() 메소드에서 반지름이 2.8, 높이가 5.6의 원통의 부피를 출력 · 다음은 원을 나타내는 클래스 Circle public class Circle { public double radius; public static double PI = 3.141592; //생성자 구현 public Circle(double radius) { this.radius = radius; } //현재 반지름을 사용하여 원의 면적을 구하는 메소드 public double getArea() { return radius * radius * PI; } } 문제 4 – 위에서 구현한 Cylinder를 다음 조건에 맞도록 기능을 추가하여 작성하시오. · 다음과 같은 객체 생성이 가능하도록 생성자를 구현 ㆍ Cylinder cd = new Cylinder(new Circle(2.8), 5.6); 문제 5 – 다음을 만족하는 클래스 SalaryMan을 작성하시오. · 필드 salary는 월 급여액를 저장하며, int형으로 초기 값으로 1000000 저장 · 메소드 getAnnualGross()는 연봉을 반환하는 메소드로 월급에 보너스 500%로 계산 · 기본 생성자에서 필드 salary의 초기 값을 사용하며, 정수형 인자인 생성자에서 인자가 월 급여액으로 지정 · 다음과 같이 객체를 생성하여 메소드 getAnnualGrass()를 호출하여 출력 System.out.println(new SalaryMan().getAnnualGross()); System.out.println(new SalaryMan(2_000_000).getAnnualGross()); 문제 6 – 다음을 만족하는 클래스 Account를 작성하시오. · 다음의 2 개의 필드를 선언 private String owner; private long balance; · 위 모든 필드에 대한 getter와 setter의 구현 · 위 모든 필드를 사용하는 가능한 모든 생성자의 구현 문제 7 – 위에서 구현된 클래스 Account에서 다음 기능을 추가하여 작성하시오. · 메소드 deposit()의 헤드는 다음과 같으며 인자인 금액을 저축하는 메소드 public long deposit(long amount) · 메소드 withdraw()의 헤드는 다음과 같으며 인자인 금액을 인출하는 메소드 public long withdraw(long amount) · Account 클래스의 main() 메소드에서 Account 객체를 생성하여 적당한 저축과 인출을 수행한 후 잔금을 출력 문제 8 – 위에서 구현된 메소드 withdraw()를 다음 조건에 맞게 다시 작성하시오. · 인출 상한 금액은 잔액까지로 하며, 이 경우 이러한 상황을 출력 · 클래스 AccountTest의 main() 메소드에서 인출 상한 이상의 금액을 인출하려는 메소드를 호출하여 출력 문제 – 9. 다음을 만족하는 클래스 Rectangle을 작성하시오. · 사각형의 가로와 세로로 객체를 생성하는 생성자 · 면적을 반환하는 메소드 getArea(), 둘레를 반환하는 메소드 getCircumference(), · 다음과 같이 클래스 Rectangle 이용 Rectangle rc = new Rectangle(3.82, 8.65); System.out.println(“면적: ” + rc.getArea()); System.out.println(“둘레: ” + rc.getCircumference()); 문제 – 10. 다음을 만족하는 클래스 Computer를 작성하시오. · 다음을 상수 필드로 선언 public … String[] osType = {“원도7”, “애플 OS X”, “안드로이드”}; · 다음과 같은 클래스 Computer의 객체의 사용 결과에 적합하도록 생성자와 메소드 구현 Computer pc = new Computer(0, 16); Computer apple = new Computer(1, 32); Computer galaxy = new Computer(2, 16); pc.print(); apple.print(); galaxy.print(); 운영체제: 원도7, 메인메모리: 16 운영체제: 애플 OS X, 메인메모리: 32 운영체제: 안드로이드, 메인메모리: 16 public cla 소스 코드 문제 1 + 2 package ex1; import java.util.Scanner; class StudentEx2{ private String name; private int id; void setName(String name) { // setter 네임 this.name = name; } String getName() { // getter id return this.name+” 학과”; } void setId(int id) { this.id = id; } int getId() { return this.id; } } public class StudentEx1 { public static void main(String[] args) { /* * 다음을 만족하는 Student 클래스를 작성하시오 * String 형의 학과와 정수형의 학번을 필드로 선언 * Student 클래스의 main()메소드에서 Student 객체를 생성하여 학과와 학번 필드에 * 적당한 값을 입력한 후 출력 * 2. 위에서 구현한 Student 클래스를 다음을 만족하도록 기능을 추가하여 작성하시오. 필드를 모두 private로 하고, getter와 setter를 구현하고 Student 클래스의 main() 메소드에서 Student 객체를 생성하여 setter를 사용하여 학과와 학번 필드에 적당한 값을 입력 후 출력 */ Scanner sc = new Scanner(System.in); StudentEx2 student1 = new StudentEx2(); System.out.println(“—회원가입—“); System.out.print(“학과 입력 :”); String name = sc.next(); student1.setName(name); System.out.print(“학번 입력 :”); int id = sc.nextInt(); student1.setId(id); System.out.println(“학생1의 학과 :”+student1.getName()+”, 학번 :”+student1.getId()); } } 문제 3+4 package ex1; public class Circle { public double radius; // 필드(==인스턴스)변수 선언 public static double PI = 3.141592; // 원주율 // 생성자 구현 public Circle(double radius) { this.radius = radius; } // 기능 구현 public double getArea() { return radius * radius * PI; // 원의 면적을 구하는 공식 반지름*반지름*파이 } } package ex1; public class Cylinder { Circle cir; double height; public Cylinder(Circle cir,double height) { // TODO Auto-generated constructor stub this.cir=cir; this.height=height; } // 생성자 구현 public double Volum() { return cir.getArea()*height; // 반지름과 높이를 곱함.. } public static void main(String[] args) { // 반지름이 2.8 , 높이가 5.6의 원통의 부피를 출력 Circle cp = new Circle(2.8); // 반지름 2.8 Cylinder cd = new Cylinder(new Circle(2.8), 5.6); // Circle 생성자의 2.8, Cylinder 5.6 double height = 5.6; // radius 2.8 height 5.6 // 부피 구하는 법 : 원의 면적 * 높이 . >> 면적은 반지름+반지름+파이 파이먹고싶다 System.out.println(“부피 : “+(cp.getArea()*height)); System.out.println(cd.Volum()); // 동일한 결과 } } /* * 3. 다음에 구현된 Circle 클래스를 참고로 다음을 만족하는 Cylinder 클래스를 작성하시오. · 원통을 나타내는 Cylinder 클래스는 Circle형의 원과 실수형의 높이를 필드로 선언 · 메소드 getVolume()은 원통의 부피를 반환 · Cylinder 클래스의 main() 메소드에서 반지름이 2.8, 높이가 5.6의 원통의 부피를 출력 · 다음은 원을 나타내는 클래스 Circle 4. 위에서 구현한 Cylinder를 다음 조건에 맞도록 기능을 추가하여 작성하시오. · 다음과 같은 객체 생성이 가능하도록 생성자를 구현 ㆍ Cylinder cd = new Cylinder(new Circle(2.8), 5.6); */ 문제 5 package Salary; public class SalaryMan { int salary; //월 급여 액 저장 초기값 1,000,000 저장 SalaryMan(){ this.salary = 1000000; } SalaryMan(int salary){ // 생성자에서 인자 월 급여액을 지정하기 위한 재정의 this.salary=salary; } public int getAnnualGross() { // 연봉.. 연봉은 월 * 12 인데 // 보너스 500%를 수령해야 하니까 5.0을 곱해야하지만 int 정수형이므로 5만 곱하고 return (this.salary*12)+(this.salary*5); // 연봉 + 500% 보너스 수령 // 연봉 리턴 } public static void main(String[] args) { SalaryMan user = new SalaryMan(); user.salary = 1500000; // 연봉 1800만 * 보너스 750만 // 최저도 못받는 인생인데 보너스가 쎄네 System.out.println(user.getAnnualGross()); System.out.println(); System.out.println(new SalaryMan().getAnnualGross()); System.out.println(new SalaryMan(2000000).getAnnualGross()); } } /* 5. 다음을 만족하는 클래스 SalaryMan을 작성하시오. · 필드 salary는 월 급여액를 저장하며, int형으로 초기 값으로 1000000 저장 · 메소드 getAnnualGross()는 연봉을 반환하는 메소드로 월급에 보너스 500%로 계산 · 기본 생성자에서 필드 salary의 초기 값을 사용하며, 정수형 인자인 생성자에서 인자가 월 급여액으로 지정 · 다음과 같이 객체를 생성하여 메소드 getAnnualGrass()를 호출하여 출력 System.out.println(new SalaryMan().getAnnualGross()); System.out.println(new SalaryMan(2_000_000).getAnnualGross()); */ 문제 6 + 7 + 8 package Account; import java.util.Scanner; class Account { private String owner; private long balance; Account(){ // default 생성자 } Account(String owner){ this.owner = owner; } Account(long balance){ this.balance=balance; } Account(String owner, long balance){ this.owner = owner; this.balance = balance; } void setOwner(String owner) { this.owner = owner; } String getOwner() { return this.owner; } void setBalance(long balance) { this.balance = balance; } long getBalance() { return this.balance; } public long deposit(long amount) { // 인자인 금액을 저축하는 기능 System.out.println(amount+”만큼 입금 합니다.”); return this.balance+=amount; //저장 } public long withdraw(long amount) { // 입력한 금액만큼 인출한 기능 Scanner sc = new Scanner (System.in); long money = amount; // 새로운 money 변수를 선언 System.out.println(“현재 고객님은 “+this.balance+”원 까지 인출할 수 있습니다.”); if(this.balance < amount ) { // 현재 값이 입력 값보다 적다면 System.out.println("잔액이 부족하여 인출하실 수 없습니다."); System.out.println("가진 금액을 모두 출금 하시겠습니까? y/n"); String se[] = {"y","n"}; String sel = sc.next(); if(sel.equals(se[0])) { money = this.balance; // 현재 돈을 money값에 대입 } } System.out.println(money+"만큼 인출 합니다."); return this.balance -= money; // money값 } void show() { System.out.println(this.owner+"님은 현재 "+this.balance+"원을 가지고 있습니다."); } } public class Main { public static void main(String[] args) { Scanner sc = new Scanner (System.in); Account player = new Account(); // 생성자 System.out.print("사용자 성함을 입력하세요 :"); String owner = sc.next(); player.setOwner(owner); System.out.print("사용자의 잔액은 얼만큼 있는지 적으세요. :"); long balance = sc.nextLong(); player.setBalance(balance); player.show(); System.out.println("얼만큼 저축 하시겠습니까?"); int amo = sc.nextInt(); player.deposit(amo); player.show(); System.out.println("얼마를 인출 하시겠습니까?"); amo = sc.nextInt(); player.withdraw(amo); player.show(); } } 9 - package Rectangle; public class Rectangle { double width; double length; Rectangle(double width, double length){ this.width=width; this.length=length; } double getArea() { // 면적 (가로*세로) return this.width * this.length; } double getCircumference() { // 둘레 (가로+높이)*2 return (this.width+this.length)*2 ; } public static void main(String[] args) { // 사각형의 가로와 세로로 객체를 생성하는 생성자 // 면적을 반환하는 메소드 getArea(), // 둘레를 반환하는 메소드 getCircumference(), // 다음과 같이 클래스 Rectangle 이용 // Rectangle rc = new Rectangle(3.82, 8.65); // System.out.println("면적 : "+rc.getArea()); // System.out.println("둘레 : "+rc.getCircumference()); Rectangle rc = new Rectangle(3.82,8.65); System.out.println("가로:3.82, 세로: 8.65"); System.out.println("면적 : "+rc.getArea()); System.out.println("둘레 : "+rc.getCircumference()); } } 10 - package Computer; class Computer{ public static final String[] osType = {"윈도우7","애플 OS X","안드로이드"}; private int OS; // 배열의 인덱스 i 역할을 할 것임 int Memory = 8; Computer(int OS,int Memory){ this.OS = OS; this.Memory = Memory; } void show() { System.out.printf("운영체제: %s, 메인메모리: %d %n", osType[OS], Memory); } } public class Main { public static void main(String[] args) { Computer pc = new Computer(0,16); Computer apple = new Computer(1,32); Computer Android = new Computer(2, 16); pc.show(); apple.show(); Android.show(); } } 반응형 04장 연습문제 (연습문제 풀이 : https://wikidocs.net/157712#04) Q1 다음 코드의 출력 결과는 무엇일까? (눈으로 해석하고 풀어보자.) public class Sample { public static void main(String[] args) { String a = “write once, run anywhere”; if (a.contains(“wife”)) { System.out.println(“wife”); } else if (a.contains(“once”) && !a.contains(“run”)) { System.out.println(“once”); } else if (!a.contains(“everywhere”)) { System.out.println(“everywhere”); } else if (a.contains(“anywhere”)) { System.out.println(“anywhere”); } else { System.out.println(“none”); } } } Q2 while문을 사용해 1부터 1000까지의 자연수 중 3의 배수의 합을 구해 보자. Q3 while문 또는 for 문을 사용하여 다음과 같이 별( * )을 표시하는 프로그램을 작성해 보자. * ** *** **** ***** Q4 for문을 사용해 1부터 100까지의 숫자를 출력해 보자. Q5 A 학급에 총 10명의 학생이 있다. 이 학생들의 중간고사 점수는 다음과 같다. int[] marks = {70, 60, 55, 75, 95, 90, 80, 80, 85, 100}; for each 문을 사용하여 A 학급의 평균 점수를 구해 보자. [22] 클래스를 활용한 연습 문제 문제) 전화번호부를 관리하는 프로그램을 만들어보자. – public class PhoneInfo 소스 코드 (class) package kosta.phone; public class PhoneInfo { // 전화번호부 관리프로그램 구현하자 (1명의 전화번호부 ) // 상태 : 이름, 전화번호, 생년월일 // 기능 : 1명의 전화내역을 출력 // 1. 각각의 상태에 따른 필드(속성)을 선언한다. String name; // 이름 String phoneNo; // 전화번호 String birth; // 생년월일 // 2. 사용할 생성자를 생성한다. (생성자는 리턴형이 존재하지 않는다.) public PhoneInfo() {} // 디폴트 생성자(기본 생성자) : 입력매개변수(파라미터)가 아무것도 없을 때를 항상 생각한다. // 3. Source 메뉴에서 필드를 통해서 만들어준다. (직접 입력도 가능하다.) public PhoneInfo(String name, String phoneNo, String birth) { super(); this.name = name; this.phoneNo = phoneNo; this.birth = birth; } // 4. 전화내역을 출력할 메서드를 생성한다. public void show() { // 출력은 리턴값이 필요하지 않기 때문에, void를 사용한다. -> void의 사용은 입력매개변수(파라미터)가 없음과도 같다. System.out.println(“이름 : “+name); System.out.println(“전화번호 : “+phoneNo); System.out.println(“생년월일 : “+birth); } // -> 상태와 기능을 구현했으면, maim() 영역으로 가자~ } – public class Manager 소스 코드 (class) package kosta.phone; import java.util.Scanner; public class Manager { Scanner sc = new Scanner(System.in); PhoneInfo[] arr = new PhoneInfo[10]; // PhoneInfo 클래스에 대한 10개의 객체를 만들었다. int count = 0; // 1. 프로그램을 구동할 세부적인 메서드(기능적인 부분)를 만들어준다. // 기능 : 전화번호 추가, 전화번호 출력, 전화번호 검색 public void addPhone() { System.out.print(“이름 : “); String name = sc.nextLine(); System.out.print(“전화번호 : “); String phoneNo = sc.nextLine(); System.out.print(“생년월일 : “); String birth = sc.nextLine(); arr[this.count++] = new PhoneInfo(name, phoneNo, birth); // 전화번호를 추가할 때마다 각각의 객체에 데이터를 추가한다. System.out.println(“전화번호가 등록되었습니다.”); } // 전화번호 추가 public void listPhone() { for (int i = 0; i < this.count; i++) { arr[i].show(); // PhoneInfo 클래스에 대한 show() 메서드를 호출 } } // 전화번호 출력 public void searchPhone() { System.out.print("이름 : "); String name = sc.nextLine(); // 찾고자하는 변수를 만들고, 입력한다. int idx = -1; // 문자열의 위치를 알기 위해서 만든 변수이다. // name 내가 쓴 문자열이 어디 있는지 모르기 때문에 하나씩 비교한다. for문으로.. for(int i = 0; i < count; i++) { PhoneInfo info = arr[i]; // 이미 생성된 객체를 변수에 넣는 것이므로, new 연산자를 사용하지 않아도 된다. if(name.equals(info.name)) { // i값은 배열의 위치를 알려준다. info.show(); idx = i; // 문자열의 존재여부를 확인 - 임시 변수! (0~9) break; // 나간다! } } if (idx == -1) { System.out.println("해당하는 정보를 찾을 수 없습니다."); } } // 전화번호 검색 //////////////////////////////////////////////////////////////////////////// // <<<<<<<<<<<<<<<<<<<<<<<<< Main() 영역 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // // 2. Manager 클래스를 Main() 영역에서 사용하기 위한 객체를 생성한다. // // < 객체를 반복적으로 생성하면 값에 영향을 주므로, Scanner 밑에 생성하는 것이 좋다. > // Manager m = new Manager(); // // // 3. 생성한 Manager 클래스에 대한 객체의 메서드(기능적인 부분)을 뼈대에 추가한다. // m.addPhone(); // m.listPhone(); // m.searchPhone(); //////////////////////////////////////////////////////////////////////////// // 4. 매서드를 하나씩 구현하기 위한 코드를 작성한다. // addPhone() {소스 코드 작성}, listPhone() {소스 코드 작성}, searchPhone() {소스 코드 작성} // 5. 전화번호의 추가와 검색에 필요한 자바 입력 API Scanner을 만든다. // Scanner sc = new Scanner(System.in); // 6. 전화번호부 관리프로그램의 상태와 기능을 담당하는 PhoneInfo 클래스의 객체를 생성한다. // PhoneInfo[] arr = new PhoneInfo[10]; // // 7.1 전화번호를 추가하는 메서드인 addPhone() {}의 소스 코드를 작성한다. // 모든 변수의 쓰임은 항상 통일해주는 것이 좋다. // String name = sc.nextLine();, String phoneNo = sc.nextLine();, String birth = sc.nextLine(); // 7.2 전화번호를 관리하는 arr[] 배열의 인덱스를 바꿔줄 수 있는 count를 선언한다. // int count = 0; // arr[count++] = new PhoneInfo(name, phoneNo, birth); // // 8. 전화번호부를 잔체출력하는 메서드인 listPhone() {}의 소스 코드를 작성한다. // for문을 사용하여, arr[]의 인덱스를 count의 멤버변수(필드)에 저장된 값에 따라서 결과를 출력한다. // 출력을 할때는, PhoneInfo 클래스의 show() 메서드를 사용한다. // <<<<<<<<<<<<< 향상된 for문을 사용하면 안된다. 각각의 인덱스에 접근할 수 없기 때문이다. >>>>>>>>>>> // 9. 전화번호부를 검색하는 메서드인 searchPhone() {}의 소스 코드를 작성한다. // idx = -1; 배열은 0부터 시작하므로, -1로 초기화한 변수를 하나 선언한다. // 이름에 대한 문자열을 비교하기 위해서, 각각의 객체의 값들을 info 변수에 넣어준다. PhoneInfo info = arr[i]; // equals 자바 APT를 통하여, if(name.equals(info.name))로 이름 문자열을 비교한다. // 있을 경우, PhoneInfo 클래스의 show 메서드로 info의 변수에 존재하는 대한 arr[idx]에 대한 데이터를 출력한다. // 없는 경우, idx의 초기값인 -1을 그대로 얻으므로써 없다라는 메세지를 출력한다. // -> 세부적인 기능을 구현했으면, 실행한다. } – public class Main 소스 코드 (Main) package kosta.phone; import java.util.Scanner; public class Main { public static void main(String[] args) { // 1. 자바 입력 API Scanner을 만든다. Scanner sc = new Scanner(System.in); Manager m = new Manager(); // Manager 클래스에 대한 객체를 하나 생성한다. // 2. 구현할 시스템의 뼈대를 만든다. // -> 뼈대 : 눈에 보이는 글씨와 사용자가 직접 입력하는 값 while (true) { System.out.println(“1.추가 2.전체 출력 3.검색 4.종료”); System.out.print(“메뉴의 번호 선택 : “); String menu = sc.nextLine(); // String 데이터형으로 받으면, 문자열을 선택하는 조건이 있어야한다. switch (menu) { // switch (menu) 입력되는 값에 따라서, case를 찾아간다. case “1”: // 1.추가 m.addPhone(); break; case “2”: // 2.전체출력 m.listPhone(); break; case “3”: // 3.검색 m.searchPhone(); break; case “4”: // 4.종료 System.out.println(“프로그램이 종료되었습니다.”); return; // 값을 반환하지 않으면, 종료의 역할을 수행한다. } } // -> 뼈대(눈에 보이는 글씨와 사용자가 직접 입력하는 값)를 구현했으면, Manager() 영역으로 가자~ } }

So you have finished reading the 자바 클래스 문제 topic article, if you find this article useful, please share it. Thank you very much. See more: 자바 클래스 예제, 자바 클래스 생성, 자바 클래스 상속 예제, 자바 객체지향 연습문제, 자바 객체 배열 문제, 자바 클래스 배열, 자바 클래스 생성자 예제, 자바 클래스 메소드 예제

키워드에 대한 정보 자바 클래스 문제

다음은 Bing에서 자바 클래스 문제 주제에 대한 검색 결과입니다. 필요한 경우 더 읽을 수 있습니다.

이 기사는 인터넷의 다양한 출처에서 편집되었습니다. 이 기사가 유용했기를 바랍니다. 이 기사가 유용하다고 생각되면 공유하십시오. 매우 감사합니다!

사람들이 주제에 대해 자주 검색하는 키워드 [자바 기초 12] 연습문제: 메소드

  • 자바
  • 프로그래밍
  • 예제
  • 입문
  • 코딩
  • 메소드
  • 연습문제
  • 난수
  • 랜덤
  • 주사위
  • 실습
  • 문제
  • 자바 메소드 연습문제
  • 자바 연비 계산
  • 자바 환전하기
  • 자바 난수
  • 자바 Math.random
[자바 #기초 #12] #연습문제: #메소드


YouTube에서 자바 클래스 문제 주제의 다른 동영상 보기

주제에 대한 기사를 시청해 주셔서 감사합니다 [자바 기초 12] 연습문제: 메소드 | 자바 클래스 문제, 이 기사가 유용하다고 생각되면 공유하십시오, 매우 감사합니다.

See also  결혼 준비 체크 리스트 | 결혼준비 순서│결혼준비 체크리스트│결혼준비 과정│결혼준비 총 정리 263 개의 가장 정확한 답변

Leave a Reply

Your email address will not be published. Required fields are marked *