프로그래밍 언어/javastudy

명품 Java Essential 7단원 실습문제 1~7

fladi 2021. 7. 17. 09:38
728x90

<1. 실수 값 5개 입력받아 가장 큰 수 출력>

 

import java.util.*;

public class app {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		Vector<Double> v = new Vector<>();
		
		for (int i = 0; i<5; i++) {
			Double temp = scanner.nextDouble();
			v.add(temp);
		}
		
		double max = -99999999;
		Iterator<Double> it = v.iterator();
		while (it.hasNext()) {
			double temp = it.next();
			if (temp > max)
				max= temp;
		}
		
		System.out.println("가장 큰 수는 " + max);
	}
}

 

저는 iterator를 이용했습니다! 어차피 순차적으로 검색해야하니까요.

 

double max = -99999999;
		for (int i =0; i<v.size(); i++) {
			if (max < v.get(i))
				max = v.get(i);
		}

이런 방법도 상관은 없죠!

 

 

 

<2. 학점 5개를 점수로 변환하여 출력>

 

import java.util.ArrayList;
import java.util.Scanner;

public class app {
	static double grade_to_score(char grade) {
		double score = 0.0;
		
		switch (grade) {
		case 'A':
			score = 4.0;
			break;
		case 'B':
			score = 3.0;
			break;
		case 'C':
			score = 2.0;
			break;
		case 'D':
			score = 1.0;
			break;
		case 'F':
			score = 0.0;
			break;
		}
		
		return score;
	}

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		ArrayList<Character> al = new ArrayList<>();

		System.out.print("빈 칸으로 분리하여 5 개의 학점을 입력(A/B/C/D/F)>>");
		for (int i = 0; i < 5; i++) {
			char temp = scanner.next().charAt(0);
			al.add(temp);
		}

		for (int i = 0; i < al.size(); i++) {
			char grade = al.get(i);
			System.out.print(grade_to_score(grade) + "  ");
		}
		System.out.println();
	}
}

grade_to_score 함수를 이용하여 점수로 변환해주었습니다.

char입력을 받으려면 저렇게 charAt메소드를 사용해주면 됩니다~!

 

 

 

<3. 해시맵 주문받기>

 

import java.util.HashMap;
import java.util.Scanner;

public class app {
	static void createMenu(HashMap<String, Integer> hash) {
		hash.put("에스프레소", 2000);
		hash.put("아메리카노", 2500);
		hash.put("카푸치노", 3000);
		hash.put("카페라떼", 3500);
	}
	
	public static void main(String[] args) {
		HashMap<String, Integer> hash = new HashMap<>();
		
		createMenu(hash);
		
		Scanner scanner = new Scanner(System.in);
		System.out.println("에스프레소, 아메리카노, 카푸치노, 카페라떼 있습니다.");
		while(true) {
			System.out.print("주문 >>");
			String input = scanner.next();
			if (input.equals("그만"))
				break;
			
			if (hash.containsKey(input)) {
				System.out.println(input + "는 " + hash.get(input) + "원 입니다.");
			}
			else
				System.out.println("다시 입력해주세요");
		}
		
		System.out.println("안녕히가세요");
	}
}

마지막엔 안녕히가세요를 추가해줬습니다.

알바했을 때가 생각나서요 ㅎ

 

 

 

<4. 어린이 키>

 

import java.util.Scanner;
import java.util.Vector;

public class Main {
	public static void main(String[] args) {
		Vector<Double> v = new Vector<>();
		Scanner scanner = new Scanner(System.in);

		System.out.println("2000~2009년까지 1년 단위로 키(cm)를 입력");
		System.out.print(">>");
		for (int i = 0; i < 10; i++) {
			double height = scanner.nextInt();
			v.add(height);
		}

		double most = 0;
		int mostyear = 0;
		for (int i = 0; i < v.size() - 1; i++) {
			double pre = v.get(i);
			double nxt = v.get(i + 1);
			if (nxt - pre > most) {
				mostyear = 2000 + i;
				most = nxt - pre;
			}
		}

		System.out.println("가장 키가 많이 자란 년도는 " + mostyear + "년 " + most + "cm");

		scanner.close();
	}
}

키가 쑥쑥 크네요

 

 

 

<5. 가장 인구가 많은 나라 출력>

 

import java.util.*;

public class Main {
	static void inputnations(HashMap<String, Integer> nations) {
		Scanner scanner = new Scanner(System.in);
		
		System.out.println("나라 이름과 인구를 5개 입력하세요.(예: Korea 5000)");
		
		for (int i = 0; i < 5; i++) {
			System.out.print("나라 이름, 인구 >> ");
			String nation = scanner.next();
			int popul = scanner.nextInt();
			nations.put(nation, popul);
		}
        
		scanner.close();
	}
	
	public static void main(String[] args) {
		HashMap<String, Integer> nations = new HashMap<>();
		
		inputnations(nations);
		
		Set<String> keys = nations.keySet();
		Iterator<String> it = keys.iterator();
		
		int bigsize = 0;
		String bignation = null;
		
		while(it.hasNext()) {
			String key = it.next();
			if (bigsize < nations.get(key)) {
				bigsize = nations.get(key);
				bignation = key;
			}
		}
		
		System.out.println("제일 인구가 많은 나라는 (" + bignation + ", " + bigsize + ")" );	
	}
}

 

저는 nations의 킷값인 나라이름을 받아 Set에 저장하고,

Iterator로 가장 인구수가 많은 나라를 순차적으로 검사했습니다.

새삼 느끼는 건데 중국 인구수 정말정말 많네요... 

 

 

 

<6. 고객 이름과 포인트 점수 관리 프로그램>

 

 

저는 PointManager라는 클래스를 따로 만들어줬습니다.

이 클래스는 필드 2개, 메소드 4개로 이루어져있습니다.

 

private HashMap<String, Integer> points; 포인트 정보를 저장할 수 있는 해시맵
private Vector names; points에 포함된 이름정보만 가진 벡터 

 

public PointManager() 생성자. 해시맵과 벡터를 만들어준다.
private void setPoint(String name, int point) name과 point를 받아 해시맵 points를 설정해주는 메소드
private void printPoint() 해시맵 points를 전부 출력해주는 메소드
public boolean go() 동작의 핵심이 되는 메소드. 이름과 포인트를 사용자에게 입력받아 setPoint입력값으로 넣어주고 printPoint메소드를 호출한다. 만약 사용자가 첫 번째 입력으로 exit를 입력할 시, false가 반환되고 프로그램이 종료된다. (디폴트 true 반환)

 

 

먼저 PointManager클래스입니다.

 

import java.util.*;

class PointManager {
	private HashMap<String, Integer> points;
	private Vector<String> names;

	public PointManager() {
		points = new HashMap<>();
		names = new Vector<>();
	}

	private void setPoint(String name, int point) {
		if (points.containsKey(name)) {
			points.remove(name);
			points.put(name, point);
		} else {
			names.add(0, name);
			points.put(name, point);
		}
	}

	private void printPoint() {
		for (int i = 0; i < names.size(); i++) {
			System.out.print("(" + names.get(i) + ", " + points.get(names.get(i)) + ")");
		}
		System.out.println();
	}

	public boolean go() {
		String name = null;
		int point = 0;

		Scanner scanner = new Scanner(System.in);

		while (true) {
			System.out.print("이름과 포인트 입력 >> ");
			name = scanner.next();
			
			if (name.equals("exit"))
				return false;
			
			try {
				point = scanner.nextInt();
				break;
			} catch (InputMismatchException e) {
				System.out.println("잘못된 입력입니다.");
				scanner.next();
			}
		}

		setPoint(name, point);
		printPoint();

		return true;
	}
}

 

 

다음은 메인

 

public class Main {
	public static void main(String[] args) {
		PointManager pm = new PointManager();
		boolean go = true;

		System.out.println("** 포인트 관리 프로그램입니다 **");
		while (go) {
			go = pm.go();
		}

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

 

포인트매니저 객체의 go메소드는 반복유무를 의미하는 true/false값을 반환합니다.

go변수는 이 메소드의 반환값을 받아 while문 반복을 제어합니다.

 

 

 

<7. 쥐의 총 이동거리>

 

import java.util.ArrayList;
import java.util.Scanner;

class Location {
	int x, y;
    
	public Location(int x, int y) {
		this.x = x;
		this.y = y;
	}
    
	public double distance(Location loc) {
		double temp = Math.pow((x - loc.x), 2) + Math.pow((y - loc.y), 2);

		return Math.sqrt(temp);
	}
}

public class Main {
	static void inputloc(ArrayList<Location> al) {
		Scanner scanner = new Scanner(System.in);
		al.add(new Location(0, 0));

		System.out.println("쥐가 이동한 위치(x, y)를 5개 입력하라.");
		for (int i = 0; i < 5; i++) {
			System.out.print(">>");
			int x = scanner.nextInt();
			int y = scanner.nextInt();
			al.add(new Location(x, y));
		}
		al.add(new Location(0, 0));
		
		scanner.close();
	}

	static double getTotalDistance(ArrayList<Location> al) {
		double total = 0;

		for (int i = 0; i < al.size() - 1; i++) {
			Location loc1 = al.get(i);
			Location loc2 = al.get(i + 1);
			double distance = loc1.distance(loc2);
			total += distance;
		}
		
		return total;
	}

	public static void main(String[] args) {
		ArrayList<Location> al = new ArrayList<>();

		inputloc(al);
		double total = getTotalDistance(al);

		System.out.println("총 이동 거리는 " + total);
	}
}

inputloc메소드는 입력값을 받아 ArrayList에 저장해주는 메소드이고,

getTotalDistance는 ArrayList안 점들의 총 거리를 계산해주는 메소드입니다.

 

저는 쥐가 너무 싫습니다.

728x90