반응형

문제

하나의 학생 정보는 Student 클래스로 표현한다. Student 클래스에는 이름, 학과, 학번, 학점 평균을 나타내는 필드가 있다. 키보드로 학생 정보를 5개 입력받아 ArrayList<Student>에 저장한 후에 ArrayList<Student>의 모든 학생 정보를 출력하는 프로그램을 작성하라.

 

소스 코드

import java.util.*;
class Student{
	private String name; // 이름
	private String Department; // 학과
	private int StudentID; // 학번
	private double Score; // 학점
	Student(String name, String Department,int StudentID, double Score){
		this.name = name;
		this.Department = Department;
		this.StudentID = StudentID;
		this.Score = Score;
	}
	public void Print(){
		System.out.println("학생 이름 : "+name);
		System.out.println("학과 이름 : "+Department);
		System.out.println("학번 : "+StudentID);
		System.out.println("학점 : "+Score);
	}
	
}
public class Main5 {
	public static void main(String[] args)
	{
		ArrayList<Student> student = new ArrayList<Student>();
		Scanner s = new Scanner(System.in);
		System.out.println("학생 5명의 정보를 입력하시오");
		for(int i = 0;i<5;i++)
		{
			System.out.print("학생 이름 : ");
			String name = s.nextLine();
			System.out.print("학과 이름 : ");
			String department = s.nextLine();
			System.out.print("학번 : ");
			int studentID = s.nextInt();
			System.out.print("학점 : ");
			double score = s.nextDouble();
			s.nextLine();
			Student temp = new Student(name,department,studentID,score);
			student.add(temp);
		}
		Iterator<Student> it = student.iterator();
		int i = 1;
		while(it.hasNext()) {
        	System.out.println();
			System.out.println(i+"번 학생");
			it.next().Print();
			i++;
		}
        s.close();
	}
}

결과

학생 5명의 정보를 입력하시오
학생 이름 : 유관순
학과 이름 : 독립
학번 : 19021216
학점 : 4.5
학생 이름 : 이순신
학과 이름 : 무예
학번 : 15450428
학점 : 4.5
학생 이름 : 세종대왕
학과 이름 : 훈민정음
학번 : 13970515
학점 : 4.5
학생 이름 : 백범 김구
학과 이름 : 독립
학번 : 18760829
학점 : 4.5
학생 이름 : 안중근
학과 이름 : 독립
학번 : 18790902
학점 : 4.5

1번 학생
학생 이름 : 유관순
학과 이름 : 독립
학번 : 19021216
학점 : 4.5

2번 학생
학생 이름 : 이순신
학과 이름 : 무예
학번 : 15450428
학점 : 4.5

3번 학생
학생 이름 : 세종대왕
학과 이름 : 훈민정음
학번 : 13970515
학점 : 4.5

4번 학생
학생 이름 : 백범 김구
학과 이름 : 독립
학번 : 18760829
학점 : 4.5

5번 학생
학생 이름 : 안중근
학과 이름 : 독립
학번 : 18790902
학점 : 4.5
반응형
반응형

문제

다음 프로그램은 ArrayList에 20개의 임의의 실수를 삽입하고 모든 실수를 출력하는 프로그램이다. 모든 실수를 출력하는 부분을 Iterator를 이용하여 수정하라

 

문제 소스

import java.util.ArrayList;
public class Main4 {
	public static void main(String[] args) {
		ArrayList<Double> a = new ArrayList<Double>();
		for(int i = 0;i<20;i++) {
			double d = Math.random()*100; // 0.0 ~ 100.0 사이의 랜덤한 실수
			a.add(d);
		}
		// 이 부분 수정
		for(int i = 0;i<20;i++)
		{
			System.out.println(a.get(i));
		}

	}

}

 

소스 코드

(사용할 클래스가 포함된 패키지 선언 방법이 모를 땐, Ctrl + Shift + o(알파벳) 누르시면 자동으로 추가해줍니다.)

import java.util.ArrayList;
import java.util.Iterator;
public class Main4 {
	public static void main(String[] args) {
		ArrayList<Double> a = new ArrayList<Double>();
		for(int i = 0;i<20;i++) {
			double d = Math.random()*100; // 0.0 ~ 100.0 사이의 랜덤한 실수
			a.add(d);
		}
		// 이 부분 수정
		Iterator<Double> it = a.iterator(); 
		// double이 아닌 Double사용해야함 기본 타입 사용 불가
		while(it.hasNext()) { // 값이 있을때 까지 실행
			double n = it.next(); // 다음 값 n에 저장
			System.out.println(n); // 출력
		}

	}

}

결과

21.682354414100423
68.12176249839573
90.18336487034124
20.390411829434807
46.864036416920825
23.31759658352963
28.144614681214698
30.33753351616787
37.83634698945536
14.969898519803415
25.001090784183265
26.670294132217432
21.390460546060865
35.468423285316895
82.38578035008013
65.66836688688392
12.958212033635984
17.656082212719248
83.61235339930406
55.07903459309939

출력결과는 컴파일 할 때마다 달라요.

반응형
반응형

문제

키보드로 10개의 나라 이름과 인구를 입력받아 저장하고, 다시 나라 이름을 키보드로부터 입력받아 인구를 출력하는 프로그램을 다음과 같이 해시맵을 이용하여 작성하라.

 

소스코드

import java.util.*;
public class Main3 {

	public static void main(String[] args) {
		HashMap<String,Integer>nations =new HashMap<String,Integer>();
		Scanner scan = new Scanner(System.in);
		
		String Contry;
		int PeopleNumber;
		
		for(int i=0;i<10;i++)
		{
			Contry = scan.next();
				PeopleNumber = scan.nextInt();
			nations.put(Contry,PeopleNumber);
		}
		
		//입력 확인을 위한 출력문
		Set<String>keys = nations.keySet();
		Iterator<String> it = keys.iterator();
		
		while(it.hasNext()) {
			String key = it.next();
			System.out.println("("+key+", "+nations.get(key)+")");
		}
		
		System.out.print("찾으시는 나라를 입력하세요 : ");
		String find = scan.next();
		if(nations.containsKey(find)) {
			System.out.println("찾으시는 나라가 존재합니다.");
			System.out.println("나라 이름 : " + find+", 인구 수 : "+nations.get(find));
		}
		else {
			System.out.println("찾으시는 나라는 Hashmap에 존재하지 않습니다");
		}
		
		
		scan.close();
	}

}

결과

한국 1 미국 2 중국 34 인도 12 일본 0 북극 2 남극 0 독일 2 아르헨티나 3 유럽 2
(독일, 2) (미국, 2) (인도, 12) (일본, 0) (중국, 34) (유럽, 2) (남극, 0) (한국, 1) (북극, 2) (아르헨티나, 3)
찾으시는 나라를 입력하세요 : 한국
찾으시는 나라가 존재합니다.
나라 이름 : 한국, 인구 수 : 1
반응형
반응형

문제

Scanner 클래스를 사용하여 5개 학점('A', 'B', 'C', 'D', 'F')을 문자로 입력받아 ArrayList에 저장하고, ArrayList를 검색하여 학점을 점수(A=4.0, B=3.0, C=2.0, D=1.0, F=0)로 변환하여 출력하는 프로그램을 작성하라.

 

소스코드

import java.util.*;
// ArrayList연습
public class Main2 {

	public static void main(String[] args) {
		ArrayList<String> array = new ArrayList<String>();
		
		Scanner scan = new Scanner(System.in);
		System.out.print("5개의 학점을 입력하세요 : ");
		for(int i =0 ;i<5;i++) {
			String temp = scan.next();
			array.add(temp);
		}
		
		for(int i = 0;i<array.size();i++) {
			String temp = array.get(i); // i번째 문자열 얻어오기
			if(temp.equals("A")) {
				System.out.println("학점 ["+temp + "] = 4.0");
			}
			else if(temp.equals("B")){
				System.out.println("학점 [" + temp + "] = 3.0");
			}
			else if(temp.equals("C")){
				System.out.println("학점 [" + temp + "] = 2.0");
			}
			else if(temp.equals("D")){
				System.out.println("학점 [" + temp + "] = 1.0");
			}
			else
				System.out.println("학점 [" + temp + "] = 0");
		}
        scan.close();
	}

}

결과

5개의 학점을 입력하세요 : A B C D F
학점 [A] = 4.0
학점 [B] = 3.0
학점 [C] = 2.0
학점 [D] = 1.0
학점 [F] = 0
반응형
반응형

문제

Scanner 클래스를 사용하여 10개의 실수 값을 키보드로부터 읽어 벡터에 저장한 후, 벡터를 검색하여 가장 큰 수를 출력하는 프로그램을 작성하라.

 

소스코드

import java.util.*;
// Vector연습
public class Main1 {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		Vector<Double> num = new Vector<Double>();
		System.out.println("10개의 실수를 입력하시오");
		for (int i = 0; i < 10; i++) {
			num.add(scan.nextDouble());
		}
		
		double max = 0.0;
		double temp = 0.0;
		Iterator<Double>it = num.iterator();
		while (it.hasNext()) {
			temp = it.next();
			max = (max > temp) ? max : temp;
		}
		System.out.println("10개의 실수 중 최대값은 : "+ max);
        scan.close();
	}

}

결과

반응형
반응형

문제

다음 프로그램은 커파일 오류가 발생한다. 소스의 어디에서 왜 컴파일 오류가 발생하는가?

 

#include<iostream>
using namespace std;

class Circle {
	int radius;
public:
	Circle(int radius = 1) { this->radius = radius; }
	int getRadius() { return radius; }
};

template<class T>
T bigger(T a, T b){ // 두 개의 매개 변수를 비교하여 큰 값을 리턴
	if (a > b)return a;
	else return b;
}

int main()
{
	int a = 20, b = 50, c;
	c = bigger(a, b);
	cout << "20과 50중 큰 값은 " << c << endl;
	Circle waffle(10), pizza(50), y;
	y = bigger(waffle, pizza);
	cout << "waffle과 pizza 중 큰 것은 반지름은 " << y.getRadius() << endl;
}

 

아래 결과와 같이 출력되도록 프로그램을 수정하라

20과 50중 큰 값은 50
waffle과 pizza 중 큰 것의 반지름은 20

 

y = bigger(waffle, pizza); 이 부분에서 클래스에 대한 비교가 없기 때문에 오류가 납니다.

 

소스코드

#include<iostream>
using namespace std;

class Circle {
	int radius;
public:
	Circle(int radius = 1) { this->radius = radius; }
	int getRadius() { return radius; }
};

template<class T>
T bigger(T a, T b){ // 두 개의 매개 변수를 비교하여 큰 값을 리턴
	if (a > b)return a;
	else return b;
}

Circle bigger(Circle a, Circle b) {
	if (a.getRadius() > b.getRadius())return a;
	else return b;
}

int main()
{
	int a = 20, b = 50, c;
	c = bigger(a, b);
	cout << "20과 50중 큰 값은 " << c << endl;
	Circle waffle(10), pizza(20), y;
	y = bigger(waffle, pizza);
	cout << "waffle과 pizza 중 큰 것은 반지름은 " << y.getRadius() << endl;
}
반응형
반응형

문제

다음 함수는 매개 변수로 주어진 int 배열 src에서 배열 minus에 들어있는 같은 정수를 모두 삭제한 새로운 int 배열을 동적으로 할당받아 리턴한다. retSize는 remove() 함수의 실행 결과를 리턴하는 배열의 크기를 전달받는다. 

int* remove(int src[], int sizeSrc, int minus[], int sizeMinus, int& retSize);

템플릿을 이용하여 remove를 일반화하라.

 

소스코드

#include<iostream>
using namespace std;
template<class T>
T* remove(T src[], T sizeSrc, T minus[], T sizeMinus, T& retSize) {


	int count = 0;
	for (int i = 0; i < sizeSrc; i++)
	{
		for (int j = 0; j < sizeMinus; j++)
		{
			if (src[i] == minus[j]) {
				src[i] = 0; //같을때 그 값을 0으로 만들고
				count++; //같은 숫자 카운트
			}
		}
	}
	
	int size = sizeSrc - count;
	T* tmp = new T[size]; //같은개수 빼기
	
	count = 0; //재사용

	for (int i = 0; i < sizeSrc; i++)
	{
		if (src[i] != 0)//0이라면 추가안함
			tmp[count++] = src[i];

	}
	retSize = count;
	return tmp;
}

int main()
{
	int x[] = { 1, 10, 100, 5, 4 };
	int y[] = { 1,5, 200, 10 };

	int retSize;
	int* z = remove(x, 5, y, 4, retSize);
	for (int i = 0; i < retSize; i++)
		cout << z[i] << ' ';

	cout << endl;
	delete[] z;
}
반응형
반응형

문제

다음 함수는 매개 변수로 주어진 두 개의 int 배열을 연결한 새로운 int 배열을 동적 할당 받아 리턴한다.

int* concat(int a[], int sizea, int b[], int sizeb);

concat가 int 배열뿐 아니라 다른 타입의 배열도 처리할 수 있도록 일반화하라.

 

소스코드

#include<iostream>
using namespace std;

template <class T>
T* concat(T a[], T sizea, T b[], T sizeb) {
	T* z = new T[sizea + sizeb];

	for (int i = 0; i < sizea+sizeb; i++)
	{
		if (i < sizea)
			z[i] = a[i];
		else
			z[i] = b[i-sizea];
	}
	return z;
}

int main() {
	int x[] = { 1, 10, 100, 5, 4 };
	int y[] = { 2, 20, 200, 10, 8 };
	int* a = concat(x, 5, y, 5);

	for (int i = 0; i < 10; i++)
		cout << a[i] << ' ';
        delete [] a;
}
반응형
반응형

문제

배열에서 원소를 검색하는 search() 함수를 템플릿으로 작성하라. search()의 첫번째 매개 변수는 검색하고자 하는 원소 값이고, 두 번째 매개 변수는 배열이며, 세 번째 매개 변수는 배열의 개수이다. search() 함수가 검색에 성공하면 true를, 아니면 false를 리턴한다. search()의 호출 사례는 다음과 같다.

 

메인함수

int x[] = { 1,10,100,5,4 };
if (search(100, x, 5))cout < , "100이 배열 x에 포함되어 있다."; // 이 cout 실행
else cout << "100이 배열 x에 포함되어 있지 않다";

 

소스코드

#include<iostream>
using namespace std;
template<class T>
T search(T n,T x[],T size) {
	for (int i = 0; i < size; i++)
		if (x[i] == n)
			return true; //맞는 값이 있으면 true리턴
	return false; //아니면 false 리턴
}

int main() {
	int x[] = { 1,10,100,5,4 };
	if (search(100, x, 5))cout << "100이 배열 x에 포함되어 있다."; // 이 cout 실행
	else cout << "100이 배열 x에 포함되어 있지 않다";
}
반응형
반응형

문제

배열의 원소를 반대 순서로 뒤집는 reverseArray() 함수를 템플릿으로 작성하라.

reverseArray()의 첫 번째 매개 변수는 배열에 대한 포인터이며 두 번째 매개 변수는 배열의 개수이다. reverseArray()의 호출 사례는 다음과 같다.

 

메인함수

int x[] = { 1,10,100,5,4 };
	reverseArray(x, 5);
	for (int i = 0; i < 5; i++)	cout << x[i] << ' '; // 4 5 100 10 1 이 출력된다.

 

소스코드

#include<iostream>
using namespace std;
template<class T>
void reverseArray(T x[], T n) {
	for (int i = 0, j = n - 1; i < n/2; i++, j--)
	{
		T tmp = x[i];
		x[i] = x[j];
		x[j] = tmp;
	}
}

int main() {
	int x[] = { 1,10,100,5,4 };
	reverseArray(x, 5);
	for (int i = 0; i < 5; i++)	cout << x[i] << ' '; // 4 5 100 10 1 이 출력된다.
}
반응형

+ Recent posts