2019년 9월 1일 일요일

[JAVA] 5명의 성적을 입력받고 성적, 총점, 평균, 학점, 등수 출력하기

import java.util.Scanner;

public class Day08Ex03 {

static final int MAX = 5;
public static void main(String[] args) {
// 성적출력 프로그램
// 5명의 성적을 입력받아 출력하는 프로그램
// 입력 : 성명, 국어점수, 영어점수, 수학점수를 입력받아서
// 출력사항 : 입력내용 출력되고 / 학생별 총점, 학생별 평균, 학생별 평균의 학점, 학생별 등수

String[] name = new String[MAX];
int[] kor = new int[MAX];
int[] eng = new int[MAX];
int[] math = new int[MAX];

int[] total = new int[MAX];
double[] avg = new double[MAX];
String[] grade = new String[MAX];
int[] rank = new int[MAX];

Scanner sc = new Scanner(System.in);

for(int i=0; i<MAX; i++){
System.out.print((i+1) + "번 학생의 이름을 입력하세요>>");
name[i] = sc.next();

do {
System.out.print((i + 1) + "번 학생의 국어성적을 입력하세요>>");
kor[i] = sc.nextInt();
} while (kor[i] < 0 || kor[i] > 100);
do {
System.out.print((i + 1) + "번 학생의 영어성적을 입력하세요>>");
} while (eng[i] < 0 || eng[i] > 100);
eng[i] = sc.nextInt();
do {
System.out.print((i + 1) + "번 학생의 수학성적을 입력하세요>>");
math[i] = sc.nextInt();
} while (math[i] < 0 || math[i] > 100);

total[i] = kor[i] + eng[i] + math[i]; // total
avg[i] = total[i] / 3; // avg

if(avg[i]>=90){
grade[i] = "A";
}else if(avg[i]>=80){
grade[i] = "B";
}else if(avg[i]>=70){
grade[i] = "C";
}else if(avg[i]>=60){
grade[i] = "D";
}else{
grade[i] = "F";
}

rank[i] = 1; // 등수를 모두 1로 초기화

} //for 입력, 총합, 평균 연산까지

for(int i=0; i<MAX; i++){
for(int j=0; j<MAX; j++){
if(i!=j && avg[i]<avg[j]){ // 똑같은건 건너뛰기
rank[i]++;
}
}

}

System.out.println("성명\t국어\t영어\t수학\t총점\t평균\t학점\t등수");
System.out.println("------------------------------------------------------------");

for(int i=0; i<MAX; i++){
System.out.printf("%s\t%d\t%d\t%d\t%d\t%.1f\t%s\t%d",
name[i], kor[i], eng[i], math[i], total[i], avg[i], grade[i], rank[i]);
System.out.println();

}

sc.close();
} // main

}

[JAVA] 배열 - 1차원 배열 합치기 / 2차원 배열에 넣기


import java.util.Arrays;

public class Day09Homework {

// 금요일 과제
public static void main(String[] args) {
int[] ar1 = { 10, 20, 30 };
int[] ar2 = { 50, 60, 70, 80 };

int[] ar3 = concatArr(ar1, ar2); // 2개의 배열 합치기 : ar1뒤에 ar2이 붙게 만듦.
int[][] ar4 = mkArr(ar1, ar2); // 2개의 배열을 2차원 배열로 만들기

printArr(ar3);
printArr(ar4);

} // main

static int[] concatArr(int[] a, int[] b){
int[] result = new int[a.length+b.length];

for(int i=0; i<a.length + b.length; i++){
if(i<a.length){
result[i] = a[i];
}else{
result[i] = b[i-a.length];
}
} //for
return result;
}

static int[][] mkArr(int[] a, int[] b) {

int[][] result = {a,b};
return result;
}

static void printArr(int[] a) {
System.out.println("1차원배열>>>");
System.out.println(Arrays.toString(a));
} // printArr() : 1차원 배열

static void printArr(int[][] a) {
System.out.println("2차원배열>>>");
for (int i = 0; i < a.length; i++) {
System.out.println(Arrays.toString(a[i]));
} // for문 - 배열의 행부분만 출력하면 한줄 씩 나오니까.

} // printArr() : 2차원 배열

}

[JAVA] 배열 예제 - 복권(lottery)

<45개 숫자 중 중복되지 않는 6개의 숫자 뽑기 여러 예제>

import java.util.Arrays;
import java.util.Random;

public class Day07Lottery {

static Random rand = new Random();

public static void main(String[] args) {
// 로또 번호 생성기
int[] lotto = new int[6];
int cnt = 0;

while (cnt < 6) {
lotto[cnt] = 1 + rand.nextInt(45);

for (int i = 0; i < cnt; i++) {
if (lotto[i] == lotto[cnt]) { // lotto[0]부터 lotto[cnt]까지 비교
cnt--; // 값이 중복이면, 값을 새로 넣고, 다시 비교해봐야 함. 해당 lotto[cnt]반복 위해 cnt--.
} // if
} // for

cnt++;
} // while

System.out.println(Arrays.toString(lotto));
}

public static void test02(String[] args) {
// 로또 번호 생성기-boolean 이용
int[] lotto = new int[6];
int cnt = 0;
boolean overlap = false; // 중복 여부 검사

while (cnt < 6) {
lotto[cnt] = 1 + rand.nextInt(45); // 1~45 중 랜덤한 6개의 숫자를 배열 lotto에 넣는다.

for (int i = 0; i < cnt; i++) {
overlap = lotto[i] == lotto[cnt]; // overlap이 true : 중복이 true면 다음 if문 실행.
if (overlap) {
cnt--;
} // if
} // for

cnt++;
} // while

System.out.println(Arrays.toString(lotto));
} //test02

public static void test03(String[] args) {
int[] lotto = new int[6];
boolean overlap = false;

for(int i =0; i<6; i++){
lotto[i] = 1+rand.nextInt(45);

for(int j=0; j<i; j++){
overlap = lotto[i]==lotto[j];
if(overlap){
i--;
}
} // for-j

} // for-i

System.out.println(Arrays.toString(lotto));

} // test03

}

======================================================
<추가 예제>

import java.util.Arrays;
import java.util.Random;

public class Day08Homework_lottery {
static Random rand = new Random();
static final int MAX = 45;

public static void test01(String[] args) {
// TODO Auto-generated method stub
int[] lotto = new int[6];
int cnt =0;

aaa: while (cnt < 6) {
lotto[cnt] = 1 + rand.nextInt(45);

for(int i=0; i<cnt; i++){
if(lotto[cnt]==lotto[i]){
continue aaa;
}
}

cnt++;
} // while

System.out.println(Arrays.toString(lotto));
} // test01

public static void test02(String[] args) {
int[] lotto = new int[6];
int cnt = 0;

while (cnt < 6) {
lotto[cnt] = 1 + rand.nextInt(45);
for(int i=0; i<cnt; i++){
if(lotto[cnt]==lotto[i]){
lotto[cnt] = 1 + rand.nextInt(45);
i = -1;
}
}
cnt++;
} // while
System.out.println(Arrays.toString(lotto));
} //test02

public static void test03(String[] args) {
int[] lotto = new int[6];
int cnt = 0;

while (cnt < 6) {
lotto[cnt] = 1 + rand.nextInt(45);
for(int i=0; i<cnt; i++){
if(lotto[cnt]==lotto[i]){
cnt--;
break;
}
}
cnt++;
} // while
System.out.println(Arrays.toString(lotto));
} //test03

public static void test04(String[] args) {
int[] lotto = new int[6];
int cnt = 0;

while (cnt < 6) {
int number = 1 + rand.nextInt(45);
boolean flag =true;

for(int i=0; i<cnt; i++){
if(number==lotto[i]){
flag = false;
break;
}
}
if(flag){
lotto[cnt] = number;
cnt++;
}
} // while
System.out.println(Arrays.toString(lotto));
} //test04

public static void test05(String[] args) {
int[] balls = new int[MAX];
int[] lotto = new int[6];
int cnt = 0;

for(int i =0; i<MAX; i++){
balls[i] = i+1; // balls에 1~45 넣기
}

while(cnt<lotto.length){
int idx = rand.nextInt(MAX); // 0~44
if(balls[idx] !=0){
lotto[cnt] = balls[idx];
balls[idx] = 0;
cnt++;
}
}

System.out.println(Arrays.toString(lotto));

} //test05

public static void test06(String[] args) {
boolean[] flags = new boolean[MAX]; // 초기화 안 해도 기본값 false
int[] lotto = new int[6];
int cnt = 0;

while(cnt<lotto.length){
int idx = rand.nextInt(MAX);
if(flags[idx] != true){
lotto[cnt] = idx+1;
flags[idx] = true;
cnt++;
}

} // while

System.out.println(Arrays.toString(lotto));
} //test06

public static void main(String[] args) {
int[] balls = new int[MAX];
int cnt =0;
while(cnt<6){
int idx = rand.nextInt(MAX);
if(balls[idx]==0){
balls[idx] = idx+1;
cnt++;
} // if
} // while

for(int i=0; i<MAX; i++){
if(balls[i]!=0){
System.out.print(balls[i] + " ");
}
} // for

} // test07 - 순서대로 정렬도 된다.

}


[JAVA] 구구단 3행 3열 출력, 입력받아서 3열씩 출력하기

<구구단 3행 3열 출력하기>

public class Day07Homework3 {

public static void test01(String[] args) {
// 구구단 3행 3열
int dan =2;

for (dan = 2; dan <= 9; dan += 3) {
for(int i =0; i<3; i++){
System.out.print(dan+i<10 ? " <" + (dan+i) + "단>\t" : "");
}
System.out.println();
for(int i=1; i<=9; i++){
for(int j =0; j<3; j++){
String str = (dan+j) + "*" + i + "=" + (dan+j)*i;
System.out.print(dan+j<10 ? str + "\t" : "");
}
System.out.println();
}
}

} // test01


}

==========================================================
<시작과 끝나는 단 입력 받아서 구구단 3열씩 출력하기>

import java.util.Scanner;

public class Day07Homework5 {
static Scanner scan = new Scanner(System.in);
static final int MIN = 2;
static final int MAX = 9;

public static void main(String[] args) {

int startDan=MIN, endDan=MAX;

System.out.println("시작 단 입력>>>");
startDan = scan.nextInt();
while(startDan<MIN || startDan>MAX){
System.out.println("다시 입력(" + MIN +"~" + MAX + ")>>>");
startDan = scan.nextInt();
} // while : 시작 단 유효성 검사

System.out.println("끝나는 단 입력>>>");
endDan = scan.nextInt();
while(endDan<MIN || endDan>MAX){
System.out.println("다시 입력(" + MIN +"~" + MAX + ")>>>");
endDan = scan.nextInt();
} // while : 끝나는 단 유효성 검사

if(startDan>endDan){
int tmp = startDan;
startDan = endDan;
endDan = tmp;
}

// 3행 3열로 출력

for (int dan = startDan; dan <= endDan; dan += 3) {
for(int i=0; i<3; i++){
System.out.print(dan+i<10 && dan+i <=(endDan)? " <" + (dan+i) + "단>\t" : "");
}
System.out.println();
for(int i=1; i<=9; i++){
for(int j =0; j<3; j++){
String str = (dan+j) + "*" + i + "=" + (dan+j)*i;
System.out.print(dan+j<10 && dan+j <=(endDan)? str + "\t" : "");
}
System.out.println();
}
}

} //main

}

[JAVA] 배열 예제 - 월, 일을 입력 받고 1년이 며칠 남았는지 출력 / 100일 후 날짜 출력


import java.util.Scanner;

public class Day06Ex04 {
static Scanner scan = new Scanner(System.in);

public static void test01(String[] args) {

int[] days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int month, day;
int total = 0;

// ex)
// 월 입력 : 8
// 일 입력: 27
// -> 1년이 ?일 남았습니다.
System.out.println("월 입력 : ");
month = scan.nextInt();

System.out.println("일 입력 : ");
day = scan.nextInt();

for (int i = 0; i < month - 1; i++) {
total += days[i];
}
total += day;

System.out.println("1년이 " + (365 - total) + "일 남았습니다");


} // end of test01

public static void main(String[] args) {
// 과제 : 월, 일을 입력 받고 100일 후 날짜 출력
int[] days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int month, day;
int day2 = 100;

System.out.println("월 입력 : ");
month = scan.nextInt();

System.out.println("일 입력 : ");
day = scan.nextInt();

day2 = day2 -(days[month-1] -day); // 입력받은 첫 번째 달 따로 처리

while (day2 > days[month%12]) {
if ((month%12) == 0) {
month = 1;
} else {
month++;
} // if-else : 다음 년도로 넘어갔을 경우 처리

day = days[month - 1];
day2 = day2 - day;
} // while

month++;

System.out.println("입력하신 날짜의 100일 뒤는 " + month + "월 " + day2 + "일 입니다.");

} // end of test02

}

========================================================
<100일 뒤 날짜 출력 다른 코드>

import java.util.Scanner;

import static java.lang.System.out;

public class Day07Homework2 {
static Scanner scan = new Scanner(System.in);
public static void hw1(String[] args) {
// 100일 뒤 날짜 계산
Scanner scan = new Scanner(System.in);
int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int month, day; // 입력받을 날짜
int dMonth, dDay; // 100일 후 날짜
int total = 0;

out.print("Input month>>>");
month = scan.nextInt();

out.print("Input day>>>");
day = scan.nextInt();


out.printf("%d월%d일의 100일 후는", month, day);

// total에 현재 달의 남은 날짜를 저장.
// 현재 달 : month, 현재 달의 인덱스 :month-1
total = days[month-1] - day;
int i = month; // 현재 달의 다음 달.
while(total < 100){
i %= 12; // 12월 일 때 처리
total += days[i];
i++;
}
// 무조건 100보다 크다.
dDay = days[i-1]-(total-100);
dMonth = i;

scan.close(); // scanner 종료
out.printf("%d월%d일입니다.\n", dMonth, dDay);

} // end of hw1 - 날짜 세기 total에 더하는 법

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int month, day; // 입력받을 날짜
int dMonth, dDay; // 100일 후 날짜
int total = 100;

out.print("Input month>>>");
month = scan.nextInt();

out.print("Input day>>>");
day = scan.nextInt();

out.printf("%d월%d일의 100일 후는", month, day);

total = 100 - (days[month-1] - day); // 현재 달의 남은 날짜를 빼준다.
int i = month%12;

while(total > days[i]){
total = total - days[i];
i++;
i %=12;
}

dMonth = i + 1;
dDay = total;


out.printf("%d월%d일입니다.\n", dMonth, dDay);

scan.close(); // scanner 종료
} // end of hw2 - 날짜 세기 total에서 빼는 법

}

[JAVA] 수열 예제, High-Low 게임


import java.util.Random;
import java.util.Scanner;

public class Day04Homework {

public static void test01(String[] args) {
// 1+2-3+4-5+6-7+8-9+10=7
int max = 10;
int min = 1;
int total = 0;

for (int i = 1; i <= max; i++) {
if (i == min) {
total += i;
System.out.print(i);
} else if (i % 2 == 0) {
total += i;
System.out.print("+" + i);
} else {
total -= i;
System.out.print("-" + i);
} // if-else
}
System.out.print("=" + total);

} // test01

public static void main(String[] args) {
// 1+1+2+3+5+8+13+21=54 피보나치 수열
int n1 = 1, n2 = 1, n3 = 0;
int max = 8; // 피보나치 수열 출력할 횟수
int sum = 0;

for (int i = 0; i < max; i++) {
n3 = n2;
sum += n3;

if (i == 0) {
System.out.print(n3);
} else {
System.out.print("+" + n3);
}

n2 = n1;
n1 = n2 + n3;

}
System.out.print("=" + sum); // 총 합
}// test02



public static void test03(String[] args) {
// 1+1-2+3-5+8-13+21=14
int n1 = 1, n2 = 1, n3 = 0;
int max = 8; // 피보나치 수열 출력할 횟수
int sum = 0;

for (int i = 0; i < max; i++) {
n3 = n2;

if (i == 0) {
System.out.print(n3);
sum += n3;
} else if(i%2==1) {
System.out.print("+" + n3);
sum += n3;
} else{
System.out.print("-" + n3);
sum -= n3;
}

n2 = n1;
n1 = n2 + n3;

}
System.out.print("=" + sum); // 총 합

} // test03

public static void test04(String[] args) {
// 난수 발생기를 이용한 High-Low Game
Random rand = new Random();
Scanner scan = new Scanner(System.in);

int min = 1, max = 100; // 범위
int sysNum = min + rand.nextInt(max); // 1 + (0~99)니까, 1에서 100 사이 난수
int cnt = 5; // 총 횟수
int userNum = 0; // 5번 입력 받아야 함.
int low = 1, high = 100; // 추측 실패 시 제공할 범위
int answer = 0; // 재시도 입력 받을 변수

System.out.println("1부터 100까지의 숫자를 입력하세요");

for (int i = 1; i <= cnt; i++) {

userNum = scan.nextInt();

if (i < 5) {

if (userNum > sysNum) {
System.out.printf("입력하신 숫자 : %d\n", userNum);
high = userNum - 1;
System.out.printf("땡! 힌트)더 작은 숫자를 입력하세요! %d~%d사이\n", low, high);
} else if (userNum < sysNum) {
System.out.printf("입력하신 숫자 : %d\n", userNum);
low = userNum + 1;
System.out.printf("땡! 힌트)더 큰 숫자를 입력하세요! %d~%d사이\n", low, high);
} else if (userNum == sysNum) {
System.out.println("정답입니다!\n");
System.exit(0);// 대신에 break?
}
} else {
System.out.println("기회를 모두 소진하였습니다 재시도는 1을 입력하세요>>>");
answer = scan.nextInt();
if (answer == 1) {
i = 1;
System.out.println("1부터 100까지의 숫자를 입력하세요");
} // 기회 모두 소진 시

} // if-else
} // for

scan.close();
} // test04

}

[JAVA] 별 찍기 여러 문제

- 실행시킬 때는 해당 testNUM을 main으로 이름 바꾸기.

import static java.lang.System.out;

public class Ch04Ex08 {

public static void test01(String[] args) {
// 별 5*5 출력
for(int cnt=0; cnt<5; cnt++){
for(int i=0; i<=cnt; i++){
out.print('*');
}
out.println();
}

}// end of test01

public static void test02(String[] args) {
// 별 삼각형 찍기
for(int i=0; i<5; i++){
for(int j=5; j>i; j--){
out.print('*');
}//j
out.println();
}//i
}// end of test02

// 역삼각형
public static void test03(String[] args) {
// 0 : *****
// 1 : ^****
// 2 : ^^***
// 3 : ^^^**
// 4 : ^^^^*
for(int i=0; i<5; i++){
for(int j=0; j<5; j++){
out.print(j<i ? " " : "*");
}
out.println();
}
} // end of test03 역삼각형 찍기

public static void test04(String[] args) {
// 0 ^^^^* 공백이 찍히는 횟수 4 (4-i)
// 1 ^^^** 3
// 2 ^^*** 2
// 3 ^**** 1
// 4 ***** 0
for(int i=0; i<5; i++){
for(int j=4; j>=0; j--){
out.print(j>i ? " " : "*");
}
out.println();
}// 조건 연산식 이용한 코드
}// end of test04

public static void test05(String[] args) {
// *****
// ****
// ***
// **
// *
// **
// ***
// ****
// *****
int end = 5;

for(int i=0; i<9; i++){
for(int j=0; j<end; j++){
out.print("*");
}//j

out.println();

if(i<4){
end--;
}else{
end++;
}
}//for


}// end of test05

public static void test06(String[] args) {
// ^^^^*
// ^^^**
// ^^***
// ^****
// *****
// ^****
// ^^***
// ^^^**
// ^^^^*
int end = 4;
int star = 1;

for(int i=0; i<9; i++){
for(int j=0; j<end; j++){
out.print("^");
}
for(int k=0; k<star; k++){
out.print("*");
}
if(i<4){
end--;
star++;
}else{
end++;
star--;
}
out.println();
}

}// end of test06

public static void test07(String[] args) {
// ^^^^*
// ^^^***
// ^^*****
// ^*******
// *********
//  *******
//   *****
//    ***
//     *
int end = 4;
int star = 1;

for(int i=0; i<9; i++){
for(int j=0; j<end; j++){
out.print(" ");
}
for(int k=0; k<star; k++){
out.print("*");
}
if(i<4){
end --;
star += 2;
}else{
end ++;
star -= 2;
}
out.println();
}//for

}// end of test07

public static void test08(String[] args) {
// ********* 
// **** ****  빈칸 1~7 (0,1,3,5,7,5,3,1칸 씩)
// ***   ***
// **     **
// *       *
// **     **
// ***   ***
// **** ****
// *********
int star = 5;
int star2 = 4;
int blank = -1;

for (int i = 0; i < 9; i++) {

for (int j = star; j > 0; j--) {
out.print("*");
} // j : 왼쪽 별 5,4,3,2,1,2,3,4,5 찍기

if (i > 0) {
for (int k = 0; k < blank; k++) {
out.print("^");
} // k : blank
} // 첫 줄 비우고, 두 번째 줄 부터 빈 칸 찍기

if (i < 4) {
star--;
blank += 2;
} else {
star++;
blank -= 2;
}

for (int x = star2; x > 0; x--) {
out.print("*");
} // x : 오른쪽 별 4,3,2,1,2,3,4 찍기

if (i > 0 && i < 7) {
star2 = (i < 4) ? (star2 -= 1) : (star2 += 1);

}// 오른쪽 별  : 찍히는 개수의 조건 연산자(첫째 줄과 마지막 줄 빼고)

out.println();
} // for : 10번 반복


}//end of test08
}

[JAVA] 정수 3개 입력 받아, 큰 수, 중간 수, 작은 수 구분하기

import java.util.Scanner;
import static java.lang.System.out;

public class Ch04Ex04Homework {

public static void main(String[] args) {
// 정수 3개를 입력 받아서 큰 수, 중간 수, 작은 수를 구분한다.
Scanner scan = new Scanner(System.in);
int a, b, c;
int max, mid = 0, min;

out.print("정수 3개 입력 >>> ");
a = scan.nextInt();
b = scan.nextInt();
c = scan.nextInt();

max = (a > b) ? a : b;
max = (max > c) ? max : c;

min = (a < b) ? a : b;
min = (min < c) ? min : c;

if(a == max){
mid = (b > c) ? b : c;
}else if(b == max){
mid = (a > c) ? a : c;
}else if(c == max){
mid = (a > b) ? a : b;
}

out.printf("최댓값은%d 중간값은%d 최솟값은%d\n", max, mid, min);
}

}

[JAVA] 점수를 기준으로 학점 세분화 하기(+,- 부호 포함)

<학점 세분화 JAVA 코드 ex) A+ A A- 등으로 분류)

import static java.lang.System.out;

import java.util.Scanner;

public class Ch04Grade{
public static void main(String[] args) {
// 학점 세분화해서 출력해주는 프로그램
Scanner scan = new Scanner(System.in);
int score = 0;
char grade = 'F';
char info = '0';

System.out.println("점수를 입력하세요 >>> ");
score = scan.nextInt();

// 0~100 사이의 점수 분류
if(score>=0 && score<=100){

if(score>=90){
grade = 'A';
}// A학점 분류

else if(score>=80){
grade = 'B';
}// B학점 분류

else if(score>=70){
grade = 'C';
}// C학점 분류

else if(score>=60){
grade = 'D';
}// D학점 분류

// + 0 - 분류하기
if(score>=60){
if(score%10>=7 || score==100){
info = '+';
}else if(score%10<=3){
info = '-';
}
out.printf("%d점은 %c%c 학점 입니다.", score, grade, info);
}// 60점 이상 점수 분류
else{
out.printf("%d점은 낙제 점수입니다.", score);// 60점 이하는 낙제
}

}// 0 ~ 100점 사이 분류

else
{
out.print("1에서 100사이의 숫자만 입력하세요.");
}// 0~100 사이의 점수가 아닐 시 출력


}// main


}

[프로그래머스] 프린터 (자바/Java)

문제 설명 일반적인 프린터는 인쇄 요청이 들어온 순서대로 인쇄합니다. 그렇기 때문에 중요한 문서가 나중에 인쇄될 수 있습니다. 이런 문제를 보완하기 위해 중요도가 높은 문서를 먼저 인쇄하는 프린터를 개발했습니다. 이 새롭게 개발한 프린터는 아래와 같은...