문제 1) Student 클래스
학번, 이름, 국어점수, 영어점수, 수학점수, 총점, 등수를 멤버로 갖는 Student 클래스를 만든다. 이 클래스의 생성자에서는 학번, 이름, 국어점수, 영어점수, 수학점수만 인수로 받아서 초기화 처리를 한다.
이 Student 객체는 List에 저장하여 관리한다.
List에 저장된 데이터들을 학번의 오름차순으로 정렬할 수 있는 내부 정렬 기준을 구현하고, 총점의 역순으로 정렬하는데 총점이 같으면 이름의 오름차순으로 정렬이 되는 외부 정렬 기준도 구현하여 정렬된 결과를 출력하시오. (클래스명 : SortByTotal)
(등수는 List에 전체 데이터가 추가된 후에 구해서 저장한다.)
class Student implements Comparable<Student>{
int stuNum;
String name;
int koreanScore;
int englishScore;
int mathScore;
int total;
int rank;
// 생성자
public Student(int studentNum, String name, int koreanScore, int englishScore, int mathScore) {
super();
this.stuNum = studentNum;
this.name = name;
this.koreanScore = koreanScore;
this.englishScore = englishScore;
this.mathScore = mathScore;
this.total = koreanScore + englishScore + mathScore;
}
public int getStuNum() {
return stuNum;
}
public void setStuNum(int stuNum) {
this.stuNum = stuNum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getKoreanScore() {
return koreanScore;
}
public void setKoreanScore(int koreanScore) {
this.koreanScore = koreanScore;
}
public int getEnglishScore() {
return englishScore;
}
public void setEnglishScore(int englishScore) {
this.englishScore = englishScore;
}
public int getMathScore() {
return mathScore;
}
public void setMathScore(int mathScore) {
this.mathScore = mathScore;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
@Override
public String toString() {
return "Student [studentNum=" + stuNum + ", name=" + name + ", koreanScore=" + koreanScore
+ ", englishScore=" + englishScore + ", mathScore=" + mathScore + ", total=" + total + ", rank=" + rank
+ "]";
}
// 학번의 오름차순으로 정렬하기
@Override
public int compareTo(Student stu) {
return Integer.compare(this.getStuNum(), stu.getStuNum());
}
}
// Student의 total의 내림차순 외부 정렬, 같으면 이름 오름차순
class SortByTotal implements Comparator<Student> {
@Override
public int compare(Student stu1, Student stu2) {
if (stu1.getTotal() == stu2.getTotal()) {
return stu1.getName().compareTo(stu2.getName());
} else {
return Integer.compare(stu1.getTotal(), stu2.getTotal()) * -1;
}
}
}
public class StudentTest {
// 등수를 구하는 메서드
public void setRanking(List<Student> studentList) {
for (Student stu1 : studentList) { // 등수를 구할 기준 데이터를 구하기 위한 반복문
int rank = 1; // 처음에는 1등으로 초기화해 놓고 시작하낟.
// 기준값보다 큰 값을 만나면 rank변수값을 증가 시킨다.
for (Student stu2 : studentList) { // 비교 대상을 나타내는 반복문
if (stu1.getTotal() < stu2.getTotal()) {
rank++;
}
}
// 구해진 등수를 Student 객체의 rank변수에 저장한다.
stu1.setRank(rank);
}
}
public static void main(String[] args) {
StudentTest test = new StudentTest();
ArrayList<Student> stuList = new ArrayList<>();
stuList.add(new Student(1,"홍길동",85,39,70));
stuList.add(new Student(3,"이순신",44,48,61));
stuList.add(new Student(7,"성춘향",34,81,92));
stuList.add(new Student(5,"강감찬",35,59,15));
stuList.add(new Student(2,"이몽룡",54,84,87));
stuList.add(new Student(4,"일지매",15,45,35));
stuList.add(new Student(6,"변학도",54,84,87));
// 등수 구하는 메서드 호출
test.setRanking(stuList);
System.out.println("정렬전");
for (Student stu : stuList) {
System.out.println(stu);
}
System.out.println("-----------------------------------------------------------------------------------------------------------------");
Collections.sort(stuList);
System.out.println("학번의 오름차순 정렬후");
for (Student stu : stuList) {
System.out.println(stu);
}
System.out.println("-----------------------------------------------------------------------------------------------------------------");
Collections.sort(stuList, new SortByTotal());
System.out.println("총점의 내림차순 정렬후");
for (Student stu : stuList) {
System.out.println(stu);
}
System.out.println("-----------------------------------------------------------------------------------------------------------------");
} // main문
} // StudentTest
문제 2) 숫자 야구 게임
Set을 이용하여 숫자 야구 게임 프로그램을 작성하시오.
컴퓨터의 숫자는 난수를 이용하여 구한다. (1 ~ 9 사이의 값 3개)
스트라이크는 S, 볼은 B로 나타낸다.
예시)
컴퓨터 난수 ==> 9 5 7
실행예시)
숫자입력 >> 3 5 6
3 5 6 ==> 1S 0B
숫자입력 >> 7 8 9
7 8 9 ==> 0S 2B
숫자입력 ==> 9 7 5
9 7 5 ==> 1S 2B
숫자입력 ==> 9 5 7
9 5 7 ==> 3S 0B
축하합니다.
4번째 만에 맞췄습니다.
public class BaseBall1 {
private ArrayList<Integer> numList; // 난수가 저장될 리스트
private ArrayList<Integer> userList; // 사용자가 입력한 값이 저장될 리스트
private int strike; // 스트라이크의 개수
private int ball; // 볼의 개수
Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
new BaseBall().gameStart();
}
public void gameStart() {
System.out.println("*******************************");
System.out.println(" 숫 자 야 구 게 임 시 작");
System.out.println("*******************************");
System.out.println();
System.out.println("1 ~ 9 사이의 서로 다른 숫자 3개를 입력하세요.");
System.out.println();
// 난수를 만드는 메서드 호출
createNum();
// 만들어진 난수 확인하기
// System.out.println("만들어진 난수 : " + numList);
int cnt = 0; // 몇번만에 맞췄는지를 저장하는 변수 선언 및 초기화
do {
cnt++;
inputData(); // 입력용 메서드 호출
ballCount(); // 볼카운트 구하는 메서드 호출
} while(strike != 3);
System.out.println();
System.out.println("축하합니다.");
System.out.println("당신은 " + cnt + "번째 만에 맞췄습니다.");
}
// 1 ~ 9 사이의 서로 다른 난수 3개를 만들어서 리스트에 저장하는 메서드
// (Set객체 이용)
public void createNum() {
Set<Integer> numSet = new HashSet<>();
Random rnd = new Random();
// 1 ~ 9 사이의 난수 3개 만들기
while (numSet.size() < 3) {
numSet.add(rnd.nextInt(9) + 1);
}
// 만들어진 난수를 List에 저장한다.
numList = new ArrayList<>(numSet);
// List의 데어터들을 섞어준다.
Collections.shuffle(numList);
} // createNum() 메서드 끝
// 사용자로부터 3개의 정수를 입력 받아 List에 추가하는 메서드
// (단, 입력한 값들은 중복되지 않아야 한다.)
public void inputData() {
int num1, num2, num3; // 입력한 값이 저장될 변수 선언
do {
System.out.print("숫자입력 >> ");
num1 = scan.nextInt();
num2 = scan.nextInt();
num3 = scan.nextInt();
if (num1 == num2 || num1 == num3 || num2 == num3) {
System.out.println("중복되는 값이 입력되었습니다. 다시 입력하세요.");
}
} while (num1 == num2 || num1 == num3 || num2 == num3);
// 입력한 값을 List에 추가하기.
userList = new ArrayList<>();
userList.add(num1);
userList.add(num2);
userList.add(num3);
} // inputData() 메서드 끝
// 스트라이크와 볼의 개수를 구해서 출력하는 메서드
public void ballCount() {
strike = 0;
ball = 0;
for (int i = 0; i < userList.size(); i++) {
for (int j = 0; j < numList.size(); j++) {
if (userList.get(i) == numList.get(j)) { // 값이 같은지 검사
if (i == j) { // 위치가 같은지 검사
strike++;
} else {
ball++;
}
}
}
}
// 구해진 결과를 출력한다.
System.out.println(userList.get(0) + ", " + userList.get(1) + ", " + userList.get(2) + " ==> " + strike + "S " + ball + "B");
} // ballCount() 메서드 끝
} // BaseBall
문제 3) 로또 구매 프로그램
로또를 구매하는 프로그램 작성하기
사용자는 로또를 구매할 때 구매할 금액을 입력하고
입력한 금액에 맞게 로또번호를 출력한다.
(단, 로또 한장의 금액은 1000원이며 최대 100장까지만 구입할 수 있고,
거스름돈도 계산하여 출력한다.)
==========================
Lotto 프로그램
--------------------------
1. Lotto 구입
2. 프로그램 종료
==========================
메뉴선택 : 1 <-- 입력
Lotto 구입 시작
(1000원에 로또번호 하나입니다.)
금액 입력 : 2500 <-- 입력
행운의 로또번호는 아래와 같습니다.
로또번호1 : 2,3,4,5,6,7
로또번호2 : 20,21,22,23,24,25
받은 금액은 2500원이고 거스름돈은 500원입니다.
==========================
Lotto 프로그램
--------------------------
1. Lotto 구입
2. 프로그램 종료
==========================
메뉴선택 : 1 <-- 입력
Lotto 구입 시작
(1000원에 로또번호 하나입니다.)
금액 입력 : 900 <-- 입력
입력 금액이 너무 적습니다. 로또번호 구입 실패!!!
==========================
Lotto 프로그램
--------------------------
1. Lotto 구입
2. 프로그램 종료
==========================
메뉴선택 : 1 <-- 입력
Lotto 구입 시작
(1000원에 로또번호 하나입니다.)
금액 입력 : 101000 <-- 입력
입력 금액이 너무 많습니다. 로또번호 구입 실패!!!
==========================
Lotto 프로그램
--------------------------
1. Lotto 구입
2. 프로그램 종료
==========================
메뉴선택 : 2 <-- 입력
감사합니다
public class LottoTest {
private Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
LottoTest test = new LottoTest();
test.lottoStart();
}
public void lottoStart() {
while(true) {
int choice = displayMenu();
switch(choice) {
case 1 :
buyLotto();
break;
case 2 :
System.out.println();
System.out.println("감사합니다.");
return;
default :
System.out.println("번호를 잘못 입력했습니다.");
System.out.println("1 또는 2를 입력하세요.");
}
}
} // lottoStart() 메서드
// 메뉴를 출력하고 사용자가 입력한 값을 반환하는 메서드
private int displayMenu() {
System.out.println();
System.out.println("==========================");
System.out.println("Lotto 프로그램");
System.out.println("--------------------------");
System.out.println("1. Lotto 구입");
System.out.println("2. 프로그램 종료");
System.out.println("==========================");
System.out.println("메뉴 선택 >> ");
return scan.nextInt();
} // displayMenu()
// 로또 판매를 처리하는 메서드
private void buyLotto() {
System.out.println();
System.out.println("Lotto 구입 시작");
System.out.println();
System.out.println("(1000원에 로또번호 하나입니다.)");
System.out.println("금액 입력 : ");
int money = scan.nextInt();
System.out.println();
if(money < 1000) {
System.out.println("입력 금액이 너무 적습니다. 로또번호 구입 실패!!!");
return;
} else if(money >= 101000) {
System.out.println("입력 금액이 너무 많습니다. 로또번호 구입 실패!!!");
return;
}
// 로또 번호 만들기
HashSet<Integer> lottoSet = new HashSet<>();
Random rnd = new Random();
// 구매할 매수 계산
int count = money / 1000;
System.out.println("행운의 로또번호는 아래와 같습니다.");
for(int i = 1; i < count; i++) {
while(lottoSet.size() < 6) {
lottoSet.add(rnd.nextInt(45) + 1);
}
ArrayList<Integer> lottoList = new ArrayList<>(lottoSet);
Collections.sort(lottoList);
System.out.print("로또번호 " + i + " : ");
for(int j = 0; j < lottoList.size(); j++) {
if (j > 0) {
System.out.print(", ");
}
System.out.print(lottoList.get(j));
}
System.out.println(); // 줄바꿈
lottoSet.clear(); // Set 비우기
} // for (i) 문 끝
System.out.println();
System.out.println("받은 금액은 " + money + "원이고 거스름돈은 " + (money % 1000) + "원 입니다.");
} // buyLotto() 메서드
} // LottoTest 클래스
'Java' 카테고리의 다른 글
[고급자바] 문제(전화번호, 호텔 관리 프로그램) (1) | 2023.03.04 |
---|---|
[고급자바] Collection(Map) (0) | 2023.03.03 |
[고급자바] equals(), hashcode() (0) | 2023.03.03 |
[고급자바] 정렬(Comparator, Comparable) (0) | 2023.03.03 |
[고급자바] Set, Ilterator (1) | 2023.03.02 |