JAVA/Do it! 자바 프로그래밍 입문

[Do it 자바 프로그래밍 입문] 07 배열과 ArrayList 연습문제

yun.data 2023. 4. 3. 12:05

 

Q1. 배열은 동일 자료형을 순서대로 관리할 때 사용하는 자료 구조입니다.

 

 

 

Q2. 206쪽의 알파벳 출력 예제에서 각 배열 요소 값을 소문자에서 대문자로 변환해 출력하세요.

public class Q2 {
	public static void main(String[] args) {
		char[] alphabets = new char[26];
		char ch = 'a';
		
		for(int i=0; i<alphabets.length; i++, ch++) {
			alphabets[i] = (char)(ch-32);
		}
		
		for(int i=0; i<alphabets.length; i++) {
			System.out.println(alphabets[i] + ", " + (int)alphabets[i]);
		}
	}
}

 

 

 

 

 

Q3. 배열 길이가 5인 정수형 배열을 선언하고, 1~10 중 짝수만을 배열에 저장한 후 그 합을 출력하세요.

public class Q3 {
	public static void main(String[] args) {
		int[] num = new int[5];

		for(int i=1, n=0; i<=10; i++) {
			if(i%2 == 0) {
				num[n] = i;
				n++;
			}
		}
		
		int sum = 0;
		for(int n : num) {sum += n;}
		System.out.println("sum: " + sum);
	}
}

 

 

 

 

 

Q4. 다음과 같이 Dog 클래스가 있습니다. DogTest 클래스와 배열 길이가 5인 Dog[] 배열을 만든 후 dog 인스턴스를 5개 이상 생성하여 배열에 추가합니다. for문과 향상돈 for문에서 Dog 클래스의 showDogInfo() 메서드를 사용하여 배열에 추가한 Dog 정보를 모두 출력하세요.

 

Dog.java

public class Dog {
	private String name;
	private String type;
	
	public Dog(String name, String type) {
		this.name = name;
		this.type = type;
	}
	
	public String getname() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public String getType() {
		return type;
	}
	
	public void setType(String type) {
		this.type = type;
	}
	
	public String showDogInfo() {
		return name + ", " + type;
	}
}

 

DogTest.java

public class DogTest {

	public static void main(String[] args) {
		Dog[] dogs = new Dog[5];
		
		dogs[0] = new Dog("C", "Chihuahua");
		dogs[1] = new Dog("B", "Bulldog");
		dogs[2] = new Dog("P", "Poodle");
		dogs[3] = new Dog("G", "Godlen Retriever");
		dogs[4] = new Dog("S", "Samoyed");
		
		// for문
		for(int i=0; i<dogs.length; i++) {
			System.out.println(dogs[i].showDogInfo());
		}
		
		System.out.println();
		// 향상된 for문
		for(Dog d : dogs) {
			System.out.println(d.showDogInfo());
		}	
	}
}

 

 

 

 

 

Q5. Q4에서 DogTestArrayList 클래스를 만들어 멤버 변수로 ArrayList를 사용합니다. Dog 인스턴스 5개를 생성하여 ArrayList에 추가하고 ArrayList의 정보를 출력하는 코드를 작성하세요.

 

DogTestArrayList.java

import java.util.ArrayList;

public class DogTestArrayList {
	public static void main(String[] args) {
		ArrayList<Dog> dogs = new ArrayList<Dog>();
		
		dogs.add(new Dog("C", "Chihuahua"));
		dogs.add(new Dog("B", "Bulldog"));
		dogs.add(new Dog("P", "Poodle"));
		dogs.add(new Dog("G", "Godlen Retriever"));
		dogs.add(new Dog("S", "Samoyed"));
		
		for(Dog d : dogs) {
			System.out.println(d.showDogInfo());
		}
	}
}