[Power Java Compact] 5장 연습문제

2021. 12. 22. 20:50·Major/Java
728x90

 

 


Chapter 5 클래스와 객체2

 

Mini Project - p172

import java.util.*;
class User {
	String userId, password;
	static int count = 0;
	
	public User(String userId, String password) {
		this.userId = userId;
		this.password = password;
	}
}
public class ch5_miniproject {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		User[] list= new User[10];
		while(true) {
			System.out.println("================================");
			System.out.println("1.Sign Up\n2.Login\n3.Print All Users\n4.Exit");
			System.out.println("================================");
			System.out.println("번호를 입력하시오: ");
			int num = sc.nextInt();
			switch(num) {
			case 1: 
				System.out.print("Id: ");
				String id = sc.next();
				System.out.print("Password: ");
				String pwd = sc.next();
				list[User.count] = new User(id, pwd);
				User.count++;
				System.out.println("================================");
				break;
			case 2:
				System.out.print("Id: ");
				String id2 = sc.next();
				System.out.print("Password: ");
				String pwd2 = sc.next();
				for(int j=0; j<User.count ; j++) {
					if(id2.equals(list[j].userId) && id2.equals(list[j].password)) {
						System.out.println("로그인 되었습니다. ");
					}else {
						System.out.println("일치하는 정보가 없습니다. ");
					}
				}
				break;
			case 3:
				for(int j=0;j<User.count;j++) {
					System.out.printf("{ %s, %s }\n", list[j].userId, list[j].password);
				}
				break;
			case 4:
				System.out.println("종료합니다. ");
				return;
			}
		}
	}
}

 

 


Exercise 

 

1. 

for(int i=0;i<values.length();i++){
    values[i] = 0;
}

2.

giveMeString(x)에 의해 null이 출력되고,

x도하나의 객체이므로 함수의 매개변수로 들어갔을 때 참조에 의한 호출이 되므로

x가 null이 되어 참조변수가 없어졌으므로 함수 자체가 실행이 안되서 문장이 출력되지 않는다.

(맞는지 몰겠음 ㅎㅎ; 직접 코드실행해보면 null만 출력됨)

 

3.

i = 3

 

4.

30, 40

 

5.

배열이 복사되는건 아니고 b의 참조변수가 a의 참조변수를 가르키게 된다. 그래서 b를 변경하면 a도 같이 변경된다.

완전하게 복사히기 위해서는 아래와 같이 해야한다.

for (int i = 0; i < a.length; i++) {
            b[i] = a[i];
}

 

6.

main 함수에서 obj1를 생성했을 때, s_instance는 null이므로 새로운 객체를 생성하게 된다.

이제 obj2를 생성하려고하면, s_instance가 static으로 선언되었기 때문에 변수가 객체의 주소를 가지게 된다.

그래서 null값이 아니므로 s_instance를 반환하게되어 결국 외부 클래스에서 Single 클래스를 하나밖에 만들 수 없다.

 

 


Programming Exercise

 

1.

class MyMetric{
	static void kiloToMile(double kilo) {
    	System.out.println(input + "을 마일로 바꾸면 " + kilo*0.621371); 
        } 
        static void mileToKilo(double mile) { 
        System.out.println(input + "을 km으로 바꾸면 " + mile*1.609344); 
        }
    } 
    public class MyMetricTest { 
    	public static void main(String[] args) {
        	MyMetric.kiloToMile(1); 
            MyMetric.mileToKilo(1); 
            } 
    }

 

2.

import java.util.Scanner;
public class Main
{
	public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	int[] seat = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

	System.out.println("------------------");
	System.out.println("0 1 2 3 4 5 6 7 8 9");
	System.out.println("------------------");
	for(int i = 0; i < 10; i++) {
		System.out.print(seat[i] + " ");
	}
    System.out.println();
	System.out.println("------------------");

	System.out.print("몇 번째 좌석을 예약하시겠습니까? ");
	int input = sc.nextInt();
	System.out.println("예약되었습니다.");

	seat[input] = 1;
	System.out.println("------------------");
	System.out.println("1 2 3 4 5 6 7 8 9");
	System.out.println("------------------");
	for(int i = 0; i < 10; i++) {
		System.out.print(seat[i] + " ");
	}
    System.out.println();
	System.out.println("------------------");

	}
}

 

3.

import java.util.Scanner;
class student {
    static int sum(int arr[]){
        int x = 0;
        for(int i=0;i<5;i++){
            x+= arr[i];
        }
        return x;
    }
    static double avg(int arr[]){
        return sum(arr)/arr.length;
    } 
}
public class Main{
	public static void main(String[] args) {
	    Scanner sc = new Scanner(System.in);
	    int member[] = new int[5];
	    for(int i=0;i<5;i++){
	        System.out.print("성적을 입력하세요: ");
	        member[i] = sc.nextInt();
	    }
	    System.out.println("합계" + student.sum(member));
	    System.out.println("평균" + student.avg(member));
	}
}

 

4.

import java.util.Scanner;
class Plane {
    private String airbus;
    private String model;
    private int num;
    static int planes = 0;
    
    Plane(String airbus, String model, int num){
        this.airbus = airbus;
        this.model = model;
        this.num = num;
        planes++;
    }
    
    Plane(){
        airbus = "";
        model = "";
        num = 0;  
        planes++;
    }
    
    void setPlane(String airbus, String model, int num){
        this.airbus = airbus;
        this.model = model;
        this.num = num;
    }
    
    void getPlane(){
        System.out.printf("식별변호:%d 모델:%s 승객수:%d\n", planes, model, num);
    }
    
    static int getPlanes(){
        return planes;
    }
    
    
}
public class Main{
	public static void main(String[] args) {
	    Scanner sc = new Scanner(System.in);
        Plane PlaneTest = new Plane();
        PlaneTest.setPlane("","aa",200);
        PlaneTest.getPlane();
        Plane PlaneTest2 = new Plane("에어버스", "bb", 300);
        PlaneTest2.getPlane();
        Plane PlaneTest3 = new Plane("", "cc", 150);
        PlaneTest3.getPlane();
	}
}

 

 

5.

import java.util.Scanner;
class BankAccount {
    int account;
    void print(){
         System.out.println("현재 잔액은 " + this.account + "입니다.");
    }
    public void transfer(int amount, BankAccount otherAccount){
        this.account -= amount;
        otherAccount.account += amount;
    }
}
public class Main{
	public static void main(String[] args) {
	    BankAccount myAccount1 = new BankAccount();
	    BankAccount myAccount2 = new BankAccount();
	    myAccount1.account = 10000;
	    myAccount1.print();
	    myAccount2.account = 0;
	    myAccount2.print();
	    myAccount1.transfer(1000, myAccount2);
	    myAccount1.print();
	    myAccount2.print();
	}
}
728x90
저작자표시 비영리 변경금지 (새창열림)

'Major > Java' 카테고리의 다른 글

[Power Java Compact] 7장 연습문제  (0) 2022.01.05
[Power Java Compact] 6장 연습문제  (0) 2021.12.29
[Power Java Compact] 4장 연습문제  (3) 2021.12.20
[Java] 문자열 안에서 단어찾기  (0) 2021.12.20
[Power Java Compact] 3장 연습문제  (0) 2021.12.15
'Major/Java' 카테고리의 다른 글
  • [Power Java Compact] 7장 연습문제
  • [Power Java Compact] 6장 연습문제
  • [Power Java Compact] 4장 연습문제
  • [Java] 문자열 안에서 단어찾기
BeNI
BeNI
코딩하는 블로그
  • BeNI
    코딩못하는컴공
    BeNI
  • 전체
    오늘
    어제
    • Menu (254)
      • My profile (1)
      • 회고 | 후기 (8)
      • Frontend (66)
        • Article (11)
        • Study (36)
        • 프로그래머스 FE 데브코스 (19)
      • Backend (0)
      • Algorithm (58)
        • Solution (46)
        • Study (12)
      • Major (111)
        • C&C++ (23)
        • Java (20)
        • Data Structure (14)
        • Computer Network (12)
        • Database (15)
        • Linux (6)
        • Architecture (3)
        • Lisp (15)
        • OS (1)
        • Security (2)
      • etc (2)
  • 링크

    • 깃허브
    • 방명록
  • 인기 글

  • 최근 댓글

  • 최근 글

  • 태그

    자료구조
    데브코스
    react
    lisp
    리팩토링
    C++
    백준
    파일처리
    Algorithm
    프로그래머스
  • hELLO· Designed By정상우.v4.10.2
BeNI
[Power Java Compact] 5장 연습문제
상단으로

티스토리툴바