티스토리 뷰

반응형

✏️ 7장 실습문제 - 1번

package ex;
import java.util.*;

public class SolveProblem {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Vector<Integer> v = new Vector<>();
        System.out.print("정수(-1이 입려될 때까지)>>>");
        while(true){
            int num = scanner.nextInt();
            if(num==-1)
                break;
            v.add(num);
        }
        System.out.println("가장 큰 수는 "+ Collections.max(v));
        scanner.close();
    }
}

 

✏️ 7장 실습문제 - 2번

package ex;
import java.util.*;

public class SolveProblem {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ArrayList<Character> grade = new ArrayList<>();
        System.out.print("6개의 학점을 빈 칸으로 분리 입력(A/B/C/D/F)>>");
        String str = scanner.nextLine();
        double sum = 0.0;
        for (int i = 0; i < str.length(); i+=2) {
            char c = str.charAt(i);
            switch (c) {
                case 'A':
                    sum += 4.0;
                    break;
                case 'B':
                    sum += 3.0;
                    break;
                case 'C':
                    sum += 2.0;
                    break;
                case 'D':
                    sum += 1.0;
                    break;
            }
        }
        System.out.println(sum/6);
        scanner.close();
    }
}

 

✏️ 7장 실습문제 - 3번

package ex;
import java.util.*;

public class SolveProblem {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        HashMap<String,Integer> nations = new HashMap<>();
        System.out.println("나라 이름과 인구를 입력하세요.(예: Korea 5000)");
        while(true){
            System.out.print("나라 이름, 인구 >> ");
            String str = scanner.nextLine();
            if(str.equals("그만"))
                break;
            StringTokenizer stringTokenizer = new StringTokenizer(str," ");
            String [] s = new String[2];
            int i = 0;
            while(stringTokenizer.hasMoreTokens()){
                s[i] = stringTokenizer.nextToken();
                i++;
            }
            nations.put(s[0],Integer.parseInt(s[1]));
        }
        while(true){
            System.out.print("인구 검색 >> ");
            String country = scanner.next();
            if(country.equals("그만"))
                break;
            Integer People = nations.get(country);
            if(People==null){
                System.out.println(country+" 나라는 없습니다.");
            }
            else
                System.out.println(country+"의 인구는 "+People);
        }
        scanner.close();
    }
}

 

✏️ 7장 실습문제 - 4번

package ex;
import java.util.*;

public class SolveProblem {
    static void Calculate(Vector<Integer> v){
        int sum=0;
        Iterator<Integer> it = v.iterator();
        while(it.hasNext()){
            sum+=it.next();
        }
        System.out.println("현재 평균 "+sum/v.size());
    }
    static void showAll(Vector<Integer> v){
        Iterator<Integer> it = v.iterator();
        while(it.hasNext()){
            System.out.print(it.next()+" ");
        }
        System.out.println();
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Vector<Integer> v = new Vector<>();
        while(true){
            System.out.print("강수량 입력 (0 입력시 종료)>> ");
            int rain = scanner.nextInt();
            if(rain==0)
                break;
            v.add(rain);
            showAll(v);
            Calculate(v);
        }
        scanner.close();
    }
}

 

✏️ 7장 실습문제 - 5번

package ex;
import java.util.*;

class Student{
    private String name, department, number;
    private double grade;

    public Student(String name, String department, String number, double grade) {
        this.name = name;
        this.department = department;
        this.number = number;
        this.grade = grade;
    }

    public String getName(){
        return name;
    }

    public String getDepartment() {
        return department;
    }

    public String getNumber() {
        return number;
    }

    public double getGrade() {
        return grade;
    }

    public void show(){
        System.out.println("이름 : " + name);
        System.out.println("학과 : " + department);
        System.out.println("학번 : " + number);
        System.out.println("학점평균 : " + grade);
    }
}
public class SolveProblem {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ArrayList<Student> arrayList = new ArrayList<>();
        System.out.println("학생 이름,학과,학점,학점평균 입력하세요.");
        for(int i=0;i<4;i++){
            System.out.print(">>");
            String str = scanner.nextLine();
            StringTokenizer stringTokenizer = new StringTokenizer(str,",");
            String [] s = new String[4];
            int index = 0;
            while (stringTokenizer.hasMoreTokens()){
                s[index] = stringTokenizer.nextToken();
                index++;
            }
            Student student = new Student(s[0],s[1],s[2],Double.parseDouble(s[3]));
            arrayList.add(student);
        }
        Iterator<Student> it = arrayList.iterator();
        while(it.hasNext()){
            Student student = it.next();
            System.out.println("이름 : " + student.getName());
            System.out.println("학과 : " + student.getDepartment());
            System.out.println("학번 : " + student.getNumber());
            System.out.println("학점평균 : " + student.getGrade());
            System.out.println("--------------------");

        }

        while(true) {
            System.out.print("학생이름 >> ");
            String s = scanner.next();
            if(s.equals("그만"))
                break;

            for(int i = 0; i < arrayList.size(); i++) {
                Student sList = arrayList.get(i);
                if(sList.getName().equals(s)) {
                    System.out.print(sList.getName() + ", ");
                    System.out.print(sList.getDepartment() + ", ");
                    System.out.print(sList.getNumber() + ", ");
                    System.out.println(sList.getGrade());
                    break;
                }
            }
        }

        scanner.close();
    }
}

 

✏️ 7장 실습문제 - 6번

package ex;
import java.util.*;

class Location {
    private double latitude, longtitude;
    private String country;

    public Location(double latitude, double longtitude, String country) {
        this.latitude = latitude;
        this.longtitude = longtitude;
        this.country = country;
    }

    public void printAll() {
        System.out.println(country+"\t"+longtitude+"\t"+latitude);
    }
}
public class SolveProblem {
    public static void main(String[] args) {
        HashMap<String,Location> hashMap = new HashMap<>();
        Scanner scanner = new Scanner(System.in);
        System.out.println("도시,경도,위도를 입력하세요.");
        for(int i=0;i<4;i++) {
            System.out.print(">>");
            String str = scanner.nextLine();
            StringTokenizer stringTokenizer = new StringTokenizer(str,",");
            String country = stringTokenizer.nextToken().trim();
            Double longtitude = Double.parseDouble(stringTokenizer.nextToken().trim());
            Double latitude = Double.parseDouble(stringTokenizer.nextToken().trim());
            Location location = new Location(latitude,longtitude,country);
            hashMap.put(country,location);
        }
        System.out.println("-----------------");
        Set<String>keys = hashMap.keySet();
        Iterator<String> it = keys.iterator();
        while(it.hasNext()){
            String country = it.next();
            Location location = hashMap.get(country);
            location.printAll();
        }
        System.out.println("-----------------");
        while(true){
            System.out.print("도시 이름>>");
            String str = scanner.next();
            Location location = hashMap.get(str);
            if(str.equals("그만"))
                break;
            if(location==null)
                System.out.println(str+"는 없습니다.");
            else
                location.printAll();
        }
        scanner.close();
    }

}

 

✏️ 7장 실습문제 - 7번

package ex;
import java.util.*;

public class SolveProblem{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("미래장학금관리시스템입니다.");
        HashMap<String,Double> hashMap = new HashMap<String, Double>();
        for(int i=0;i<5;i++){
            System.out.print("이름과 학점>> ");
            String str = scanner.nextLine();
            StringTokenizer stringTokenizer = new StringTokenizer(str," ");
            String name = stringTokenizer.nextToken().trim();
            Double grade = Double.parseDouble(stringTokenizer.nextToken().trim());
            hashMap.put(name,grade);
        }
        System.out.print("장학생 선발 학점 기준 입력>> ");
        Double cut = scanner.nextDouble();
        System.out.print("장학생 명단 : ");
        Set<String> S =  hashMap.keySet();
        Iterator<String> it = S.iterator();
        while(it.hasNext()){
            String name = it.next();
            double grade = hashMap.get(name);
            if(grade>=cut)
                System.out.print(name+" ");
        }
        scanner.close();
    }
}

 

✏️ 7장 실습문제 - 8번

package ex;
import java.util.*;

public class SolveProblem{



    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("** 포인트 관리 프로그램입니다 **");
        HashMap<String,Integer> hashMap = new HashMap<>();
        while(true){
            System.out.print("이름과 포인트 입력>> ");
            String str = scanner.nextLine();
            if(str.equals("그만"))
                break;
            StringTokenizer stringTokenizer = new StringTokenizer(str," ");
            String name = stringTokenizer.nextToken().trim();
            Integer point = Integer.parseInt(stringTokenizer.nextToken().trim());
            if(hashMap.containsKey(name)){
                point += hashMap.get(name);
                hashMap.put(name,point);
            }
            else
                hashMap.put(name,point);
            printList(hashMap);
        }
    }


    private static void printList(HashMap<String,Integer> hashMap) {
        Set<String> s = hashMap.keySet();
        Iterator<String> it = s.iterator();
        while(it.hasNext()){
            String name = it.next();
            Integer point = hashMap.get(name);
            System.out.print("("+name+","+point+")");
        }
        System.out.println();
    }
}

 

✏️ 7장 실습문제 - 9번

package ex;
import java.util.*;

interface IStack<T>{
    T pop();
    boolean push(T ob);
}
class MyStack<T> implements IStack<T>{

    private Vector<T> v;
    private int size;
    public MyStack(){
        v = new Vector<>();
        size=-1;
    }
    @Override
    public T pop() {
        if(size==-1)
            return null;
        return v.get(size--);
    }

    @Override
    public boolean push(T ob) {
        v.add(ob);
        size++;
        return true;
    }
}

public class SolveProblem{
    public static void main(String[] args) {
        IStack<Integer> stack = new MyStack<>();
        for(int i=0; i<10; i++)
            stack.push(i);
        while(true){
            Integer n =stack.pop();
            if(n==null)
                break;
            System.out.print(n+" ");
        }
    }
}

 

✏️ 7장 실습문제 - 10번

package ex;
import java.sql.SQLOutput;
import java.util.*;
class Shape{
    public Shape next;

    public Shape() {
        next=null;
    }
    public void draw(){
        System.out.println("Shape");
    }
}
class Line extends Shape{
    @Override
    public void draw() {
        System.out.println("Line");
    }
}
class Rect extends Shape{
    @Override
    public void draw() {
        System.out.println("Rect");
    }
}
class Circle extends Shape{
    @Override
    public void draw() {
        System.out.println("Circle");
    }
}
class GraphicEditer{
    private String name;
    private Scanner scanner;
    Vector<Shape>v;

    public GraphicEditer(String name) {
        this.name = name;
        v=new Vector<>();
        scanner = new Scanner(System.in);
    }
    void run(){
        System.out.println("그래픽 에디터 beauty을 실행합니다.");
        while(true){
            System.out.print("삽입(1), 삭제(2), 모두 보기(3), 종료(4)>>");
            int option = scanner.nextInt();
            int num;
            switch (option){
                case 1:
                    System.out.print("Line(1), Rect(2), Circle(3)>>");
                    num = scanner.nextInt();
                    insert(num);
                    break;
                case 2:
                    System.out.print("삭제할 도형의 위치");
                    num = scanner.nextInt();
                    delete(num);
                    break;
                case 3:
                    print();
                    break;
                case 4:
                    System.out.println(name+"을 종료합니다.");
                    scanner.close();
                    return;
                default:
                    System.out.println("잛못 입력했습니다.");
            }

        }
    }
    public void insert(int num){
        Shape shape;
        switch (num){
            case 1:
                shape = new Line();
                break;
            case 2:
                shape = new Rect();
                break;
            case 3:
                shape = new Circle();
                break;
            default:
                System.out.println("잘못 입력했습니다.");
                return;
        }
        v.add(shape);
    }
    public void delete(int num){
        if(num-1>=v.size()||num<=0){
            System.out.println("삭제할 수 없습니다.");
            return;
        }
        v.remove(num-1);
    }
    public void print(){
        for(int i=0;i<v.size();i++){
            v.get(i).draw();
        }
    }
}

public class SolveProblem{
    public static void main(String[] args) {
        GraphicEditer graphicEditer = new GraphicEditer("beauty");
        graphicEditer.run();
    }
}

 

✏️ 7장 실습문제 - 11번

//11-1
import java.util.Scanner;
import java.util.Vector;

class Nation {
    private String country;
    private String capital;

    public Nation(String country, String capital) {
        this.country = country;
        this.capital = capital;
    }

    public String getCountry() {
        return country;
    }
    public String getCapital() {
        return capital;
    }
}

class Game {
    private Vector<Nation> v;
    private Scanner sc;

    public Game() {
        sc = new Scanner(System.in);
        v = new Vector<Nation>();
        v.add(new Nation("한국", "서울"));
        v.add(new Nation("그리스", "아테네"));
        v.add(new Nation("호주", "시드니"));
        v.add(new Nation("이탈리아", "로마"));
        v.add(new Nation("독일", "베를린"));
        v.add(new Nation("멕시코", "멕시코시티"));
        v.add(new Nation("영국", "런던"));
        v.add(new Nation("중국", "베이징"));
    }

    public void run() {
        System.out.println("**** 수도 맞추기 게임을 시작합니다. ****");
        while(true) {
            System.out.print("입력:1, 퀴즈:2, 종료:3>> ");
            int input = sc.nextInt();

            switch(input) {
                case 1:
                    insert();
                    break;
                case 2:
                    quiz();
                    break;
                case 3:
                    System.out.println("게임을 종료합니다.");
                    return;
                default :
                    System.out.println("잘못 입력했습니다.");
            }
        }
    }

    public void insert() {
        System.out.println("현재 " + v.size() + "개 나라와 수도가 입력되어 있습니다.");
        while(true){
            System.out.print("나라와 수도 입력" + (int)(v.size() + 1) + ">> ");
            String country = sc.next();
            if(country.equals("그만"))
                break;
            String capital = sc.next();

            for(int i = 0; i < v.size(); i++) {
                if(v.get(i).getCountry().equals(country)) {
                    System.out.println(country + "는 이미 있습니다!");
                    v.remove(v.size()-1);
                    break;
                }
            }
            v.add(new Nation(country, capital));
        }
    }

    public void quiz() {
        while(true) {
            int r = (int) (Math.random() * v.size());

            Nation n = v.get(r);
            String country = n.getCountry();
            String capital = n.getCapital();
            System.out.print(country + "의 수도는? ");
            String answer = sc.next();

            if(answer.equals("그만"))
                break;

            if(answer.equals(capital)){
                System.out.println("정답입니다!");
            } else System.out.println("아닙니다!");
        }
    }
}

public class Prac11_1 {
    public static void main(String[] args) {
        Game game = new Game();
        game.run();
    }
}


// 11-2
import java.util.*;

class HashMapGame {
    private Scanner sc;
    private String country, capital;

    HashMap<String, String> map;

    public HashMapGame() {
        sc = new Scanner(System.in);

        map = new HashMap<>();
        map.put("한국", "서울");
        map.put("그리스", "아테네");
        map.put("호주", "시드니");
        map.put("이탈리아", "로마");
        map.put("독일", "베를린");
        map.put("멕시코", "멕시코시티");
        map.put("영국", "런던");
        map.put("중국", "베이징");
    }

    public void insert() {
        System.out.println("현재 " + map.size() + "개 나라와 수도가 입력되어 있습니다.");
        while(true){
            System.out.print("나라와 수도 입력" + map.size() + ">> ");
            String country = sc.next();
            if(country.equals("그만"))
                break;
            String capital = sc.next();

            if(map.containsKey(country)) {
                System.out.println(country + "는 이미 있습니다!!");
                continue;
            }

            map.put(country, capital);
        }
    }

    public void quiz() {
        while(true){
            Set<String> key = map.keySet();
            Object [] arr = (key.toArray());
            int r = (int)(Math.random() * arr.length);

            System.out.print(arr[r] + "의 수도는? ");
            String answer = sc.next();

            if(answer.equals("그만"))
                break;

            if(answer.equals(map.get(arr[r])))
                System.out.println("정답입니다!");
            else System.out.println("아닙니다!");
        }
    }

    public void run() {
        System.out.println("**** 수도 맞추기 게임을 시작합니다. ****");
        while(true) {
            System.out.print("입력:1, 퀴즈:2, 종료:3>> ");
            int input = sc.nextInt();

            switch(input) {
                case 1:
                    insert();
                    break;
                case 2:
                    quiz();
                    break;
                case 3:
                    System.out.print("게임을 종료합니다.");
                    return;
                default :
                    System.out.println("잘못 입력했습니다.");
            }
        }
    }
}

public class Prac11_2 {
    public static void main(String[] args) {
        HashMapGame hashMapGame = new HashMapGame();
        hashMapGame.run();
    }
}

 

✏️ 7장 실습문제 - 12번

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

class Word {
    private String engWord;
    private String korWord;

    public Word(String engWord, String korWord) {
        this.engWord = engWord;
        this.korWord = korWord;
    }

    public String getEngWord() {
        return engWord;
    }

    public String getKorWord() {
        return korWord;
    }
}

class WordQuiz {
    private String name;
    private Scanner sc;
    private Vector<Word> v;
    final int MAX = 4;
    int[] question;

    public WordQuiz() {
        name = "명품영어";
        question = new int[MAX];
        sc = new Scanner(System.in);
        v = new Vector<Word>();
        v.add(new Word("love", "사랑"));
        v.add(new Word("painting", "그림"));
        v.add(new Word("bear", "곰"));
        v.add(new Word("eye", "눈"));
        v.add(new Word("society", "사회"));
        v.add(new Word("human", "인간"));
        v.add(new Word("picture", "사진"));
        v.add(new Word("apple", "사과"));
        v.add(new Word("head", "머리"));
        v.add(new Word("water", "물"));
        v.add(new Word("nose", "코"));
        v.add(new Word("book", "책"));
        v.add(new Word("pencil", "연필"));
        v.add(new Word("store", "상점"));
    }

    public void run() {
        System.out.println("**** 영어 단어 테스트 프로그램 \"" + name + "\" 입니다. ****");
        while(true) {
            System.out.print("단어 테스트:1, 단어 삽입:2, 종료:3>> ");
            int input = sc.nextInt();

            switch(input) {
                case 1:
                    test();
                    break;
                case 2:
                    insertQuiz();
                    break;
                case 3:
                    System.out.print("\"" + name + "\" 를 종료합니다.");
                    sc.close();
                    return;
            }
        }
    }

    public void test() {    // 1번 단어 테스트를 위한 메소드
        System.out.println("현재 " + v.size() + "개의 단어가 들어 있습니다. -1을 입력하면 종료합니다.");
        while(true) {
            randomQuiz();   // 랜덤한 값을 가진 문제 배열 생성 메소드 호출
            int answerNumber = (int)(Math.random() * question.length);  // 0~3 중 한 값을 정답번호로 저장
            int answerIndex = question[answerNumber];   // 정답번호의 배열에 있는 값이 정답
            System.out.println(v.get(answerIndex).getEngWord() + "?");  // 정답의 영어단어를 호출해 문제로 낸다.
            for(int i = 0; i < question.length; i++) {  // 4개의 보기를 만들기 위한 반복문
                System.out.print("(" + (i + 1) + ")" + v.get(question[i]).getKorWord() + " ");
                // 0~3까지 배열에 값을 넣어 각 인덱스의 보기 출력
            }
            System.out.print(">> ");
            int input = 0;
            try {   // 예외가 발생할 수 있는 숫자 실행문을 try 블록에 넣는다.
                input = sc.nextInt();
            }
            catch(InputMismatchException e) {   // 정수가 아닌 문자열을 입력하면 예외 발생
                System.out.println("숫자를 입력하세요 !!");
                sc.next();  // 현재 입력 스트림에 남아 있는 토큰 지우기
                continue;   // 다음 루프
            }

            if(input == -1){
                System.out.println();
                break;
            }
            else if(input - 1 == answerNumber) // 입력한 값은 1~4이므로
                System.out.println("Excellent !!");
            else
                System.out.println("No. !!");
        }
    }

    public void insertQuiz() {  // 2번 단어 삽입을 위한 메소드
        System.out.println("영어 단어에 그만을 입력하면 입력을 종료합니다.");
        while(true) {
            System.out.print("영어 한글 입력 >> ");
            String engWord = sc.next();

            if(engWord.equals("그만")) {
                System.out.println();
                break;
            }

            String korWord = sc.next();

            v.add(new Word(engWord, korWord));
        }
    }

    public void randomQuiz() {  // 4개의 보기에 임의의 벡터 인덱스를 주기 위한 메소드
        for(int i = 0; i < MAX; i++) {  // 보기 0 ~ 3 (실제론 1 ~ 4) 의 인덱스에
            question[i] = (int)(Math.random() * v.size());  // 0 ~ 문제의 개수(벡터의 사이즈) 중 임의의 값 저장
            for(int j = 0; j < i; j++) {    // 중복된 값은 없도록 한다.
                if(question[i] == question[j]) {
                    i--;
                    continue;
                }
            }
        }
    }
}

public class Prac12 {
    public static void main(String[] args) {
        WordQuiz wordQuiz = new WordQuiz();
        wordQuiz.run();
    }
}

 

✏️ 7장 실습문제 - 13번

//

 

✏️ 7장 실습문제 - 14번

//
반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함