package Homework;
class Circle{ //클래스 Circle 선언
double radius = 1.0; //반지름 필드 선언
public Circle(double radius) {
// Circle에 double값을 인자로 받겠다.
// 그 인자의 이름이 radius
}
public Circle() {
// 생성자
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) { //리턴값이 없는 메소드
this.radius=radius;
}
public double getArea() { //면적
double area = radius * radius * Math.PI;
return Math.round(area*100)/100.0;
}
public double getCircumference() { //둘레
double circumference = (2*radius)*Math.PI;
return Math.round(circumference*100)/100.0;
}
public String toString() { //리턴값이 반드시 String값인 메소드
return "Circle[radius="+this.radius+"]";
}
}
public class CircleEx { //클래스 접근권한 public
public static void main(String[] args) {
Circle circle= new Circle();
circle.setRadius(1.0);
System.out.println(circle.toString()+"의 둘레는
"+circle.getCircumference()+", 면적은 "+circle.getArea());
circle.setRadius(2.0);
System.out.println(circle.toString()+"의 둘레는 "
+circle.getCircumference()+", 면적은 "+circle.getArea());
}
}
코드로 설명해보았습니다.
제 코드에 보면 public class가 한개 뿐인데요
그 이유는 하나의 파일에 클래스가 둘 이상 있다면, 하나만 public으로 선언할 수 있고 해당 클래스 이름은 소스 파일 이름과 동일해야 하기 때문입니다.
객체는 new키워드를 통해서 생성할 수 있습니다.
아래는 atm 예제입니다.
package Homework;
import java.util.Scanner;
class Account{
String id;
String name;
int balance=0;
public Account(String id, String name) {
this.id=id; //생성자선언
this.name=name;
}
public Account(String id, String name, int balance) {
this.id=id; // 생성자선언
this.name=name;
this.balance=balance;
}
public String getId() {
return id; //아이디 가져오기
}
public String getName() {
return name; //이름 가져오기
}
public int getBalance() {
return balance; //잔고 가져오기
}
public int deposit(int ammount) { //입금할 때에 입금할 양 (ammount)
//입력하면 객체의정보를 받아와서 누가 입금하는지
//(getName())과 ammount로 출력해준다
System.out.printf("%s님이 %d원을 입금하였음\n",getName(),ammount);
return balance =balance+ammount; //그 뒤에 잔고에 입력한 금액을 더해줌
}
public int withdraw(int ammount) {// 출금 , 출금할 때에 얼마를 출금할건지 ammount로 입력받음
System.out.printf("%s님이 %d원을 출금하였음\n", getName(),ammount); //이름과 얼마출금하는지출력
return balance = balance-ammount; //잔고 = 잔고-출금금액
}
public int transferTo(Account another, int amount) { //송금받을 사람, 금액 입력
if (amount<= balance) { //만약 송금할 금액이 잔고보다 적다면 송금 가능하므로
System.out.printf("%s님이 %s님에게 %d원을 송금하였음\n",
getName(),another.name,amount); //송금하려는 사람(나)와 송금받을사람의 이름
//여기서 주의할 점은 transferTo 메소드에서 이름으로 String값으로 입력받는게 아닌 another이라는
//객체로 입력받기 때문에 Account에서 갖고있는 필드값의 이름으로 저장해주는 것이 좋음****
//따라서 another.name으로 호출! 그리고 얼마 송금할건지 입력햇던 ammount보여줌
balance = balance-amount; //송금에 성공했으므로 잔고에서 송금할 금액을 빼줌
another.balance = another.balance + amount; //송금받은 사람의 잔고도 늘어나야하기
//때문에 another.balance에도 amount만큼 더해줌
}else { //송금할 금액이 전고보다 크다면 송금이 불가능 하므로
System.out.printf("%s이 %s에게 %d원 송금 시도\n",getName(),another.name,amount);
System.out.println("송금액이 잔액 초과!!");
}
return balance;
}
public String toString() {
return String.format("Account[id=%s, name=%s, balance=%d]",
this.getId(),this.getName(),this.getBalance());
}
}
public class AccountEx {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
//Account account = new Account(null,null);
Account[] accountArr = new Account[3];
for(int i=0; i<accountArr.length; i++) {
//입력받아서 배열에 저장하기
// accountArr[i].id=scan.next();
// accountArr[i].name=scan.next();
// accountArr[i].balance=scan.nextInt();
accountArr[i]= new Account(scan.next(),
scan.next(),scan.nextInt()); //이렇게 받는게 깔끔함, 매개변수 수 맞추기 중요
}
System.out.println("초기 계좌 정보");
for(int i=0; i<accountArr.length; i++) {
System.out.println(accountArr[i].toString());
}
System.out.println("------------------------"); //돈이 막 움직이도록 해봤음
accountArr[0].transferTo(accountArr[1], 30000);
accountArr[0].deposit(50000);
accountArr[0].transferTo(accountArr[1], 30000);
accountArr[2].withdraw(4500);
System.out.println("------------------------");
System.out.println("은행 업무 이후 계좌 정보");
for(int i=0; i<accountArr.length; i++) { // 돈이 움직인 후에 어떻게 변화됐는지 보여주기
System.out.println(accountArr[i].toString());
}
}
}
Account[] accountArr = new Account[3]; 처럼 Account class를 배열로 선언해서 사이즈가 3인 배열을 생성할 수 도 있습니다
accountArr[i]= new Account(scan.next(),
scan.next(),scan.nextInt());
처럼 Account객체를 new 키워드로 생성해주고 이것을 accountArr 배열에 다시 저장할 수도 있습니다.
환율 계산 프로그램 예제입니다
class CurrencyConverter{ //환율 변환 프로그램.. 원리가 너무어려움 복습필요
private static double rate;
public static double toDallar(double won) { //원을 입력받아서 달러로변환
//한국 원화를 달러로 반환
return
Math.round((won/rate)*100)/100.0; // 소수점 2자리 보여주기위해 math함수 이용
//입력받은 won을 rate(1180원)로 나누면 결국 몇달라를 환율할 수 있을지 나오는 것이니 그걸 return
}
public static double toKWR(double dollar) { //달러를 입력받아 원으로 변환
//달러를 한국 원화로 변환
return
Math.round((dollar*rate)*100)/100.0; // 환율 자체가 1달러당 1180원이라 곱해서 return
}
public static void setRate(double r) { //r이 환율인듯
//환율 설정 kwr/$1
rate=r; //환율을 뭘 기준으로 잡을지 정해야함. 나는 1달라당 1180.64원이니까
//환율을 1180.64로 설정
}
}
public class CurrencyConverterEx {
public static void main(String[] args) {
// 오늘 미국 달러 환율 적용
CurrencyConverter.setRate(1180.64); //환율 설정
CurrencyConverter.toDallar(1000000); //원을 달라로 계산
CurrencyConverter.toKWR(100); //달라를 원으로 계산만
System.out.println("백만원은 "+CurrencyConverter.toDallar(1000000)+"달라입니다.");
System.out.println("백달러는 "+CurrencyConverter.toKWR(100)+"원입니다.");
}
}
클래스 외부에서 객체의 멤버 접근
CurrencyConverter.setRate(1180.64);
처럼 클래스이름.메소드이름으로 접근할 수 있습니다
클래스 내부에서 멤버 접근
위의 환율 계산 프로그램의 코드에는 없지만
그 위의 atm 예제에 보시면
public Account(String id, String name) {
this.id=id; //생성자선언
this.name=name;
}