Day 25 (23.01.31)

Jane·2023년 1월 31일
0

IT 수업 정리

목록 보기
25/124

1. 지난 시간 복습 ~ Scanner 예제

1-1. 총점, 평균, 학점 구하는 코드

import java.util.Scanner;

class Grade {
	private int kor;
	private int eng;
	private int math;

	public Grade(int kor, int eng, int math) {
		this.kor = kor;
		this.eng = eng;
		this.math = math;
	}

	public int getSum() {
		return kor + eng + math;
	}

	public double getAvg() {
		return getSum() / 3.0;
	}

	public char getGrade() {
		char ch = '가';
		if (getAvg() >= 90) {
			ch = '수';
		} else if (getAvg() >= 80) {
			ch = '우';
		} else if (getAvg() >= 70) {
			ch = '미';
		} else if (getAvg() >= 60) {
			ch = '양';
		} else {
			ch = '가';
		}
		return ch;
	}

	public void show() {
		System.out.println("총점 : " + getSum());
		System.out.println("평균 : " + getAvg());
		System.out.println("성적 : " + getGrade() + "입니다");
	}

}

public class JavaTest {

	public static void main(String[] args) {
		int kor, eng, math;
		Scanner sc = new Scanner(System.in);
		System.out.print("국어 : ");
		kor = sc.nextInt();
		System.out.print("영어 : ");
		eng = sc.nextInt();
		System.out.print("수학 : ");
		math = sc.nextInt();

		Grade a = new Grade(kor, eng, math);
		a.show();

	}

}

1-2. 반복하기 (1-1에서 main() 수정)

  • main 함수에서 while문 돌린다.
  • yes, no를 입력받고 while문을 탈출한다.
public class JavaTest {

	public static void main(String[] args) {
		int kor, eng, math;
		Scanner sc = new Scanner(System.in);

		while (true) {
			System.out.print("국어 : ");
			kor = sc.nextInt();
			System.out.print("영어 : ");
			eng = sc.nextInt();
			System.out.print("수학 : ");
			math = sc.nextInt();

			Grade a = new Grade(kor, eng, math);
			a.show();

			// while문 안에서 계속할지 물어보기
			System.out.println("계속 하시겠습니까? : ");
			String yn = sc.next();
			if (yn.equals("y") || yn.equals("yes")) {
				continue;
			} else {
				break;
			}
		} // end of while
        
		System.out.println("종료합니다");
	}

}

2. 배열 (Array)

  • 선언하기
    int[] ref = new int[5];
    참조형 데이터 타입 (int[], int 배열)
  • 배열은 생성자가 오지 않는다.

2-1. 배열의 길이

  • 배열의 멤버 변수 : length
public class JavaPractice {

	public static void main(String[] args) {

		int[] ar1 = new int[5];
		double[] ar2 = new double[7];
		float[] ar3 = new float[9];
		
		System.out.println("배열 ar1 길이 : " + ar1.length);
		System.out.println("배열 ar2 길이 : " + ar2.length);
		System.out.println("배열 ar3 길이 : " + ar3.length);
	}

}

[Console]
배열 ar1 길이 : 5
배열 ar2 길이 : 7
배열 ar3 길이 : 9

2-2. 배열을 적용한 코드 (1-1에서 수정)

Grade 클래스 안의 변수와 함수 수정

private int[] score = new int[3];

public Grade(int kor, int eng, int math) {
	score[0] = kor;
	score[1] = eng;
	score[2] = math;
}

public int getSum() {
	return score[0] + score[1] + score[2];
}

변수를 좀 더 확실하게 하고 싶다면?

final int SUB_MAX = 3;
private int[] score = new int[SUB_MAX];

2-3. 배열에 숫자를 보관하고 합 구하기

  • 10개의 int를 담을 수 있는 배열을 만든다
  • 배열 안에 담긴 수의 합을 구한다
public class JavaPractice {

	public static void main(String[] args) {

		int[] arr = new int[10];
		int sum = 0;

		for (int i = 0; i < arr.length; i++) {
			arr[i] = i + 1;
			sum += arr[i];
		}

		System.out.println("arr의 합 : " + sum);
	}

}

[Console]
arr의 합 : 55

2-4. 로또 번호 출력 코드

public class JavaPractice {

	public static void main(String[] args) {

		int[] lotto = new int[6]; // 로또 번호를 담을 배열
		int temp; // 순서 바꾸기 할 때 사용할 임시 변수

		// Math.random()으로 로또 번호 얻어오기
		for (int i = 0; i < lotto.length; i++) {
			lotto[i] = (int) ((Math.random() * 45) + 1);

			// 중복 제거하기
			for (int j = 0; j < i; j++) {
				if (lotto[i] == lotto[j]) {
					i--;
                    // 같은 번호가 있으면 for문의 매개변수 하나를 줄여서 다시 수를 얻어오도록 한다
				}
			}

		}

		// 숫자를 오름차순으로 정렬
		for (int i = 0; i < lotto.length; i++) {
			for (int j = i + 1; j < lotto.length; j++) {

				// 앞의 수가 뒤의 수보다 크면 서로 자리 바꾸기
				if (lotto[i] > lotto[j]) {
					temp = lotto[i];
					lotto[i] = lotto[j];
					lotto[j] = temp;
				}
			}
		}


		// 로또 번호 출력하기
		for (int i = 0; i < lotto.length; i++) {
			System.out.print(lotto[i] + " ");
		}
	}

}

3. 예제

3-1. 총점. 평균. 학점 구하기 (콘솔 입력 + 배열 포함)

import java.util.Scanner;

class Grade {
	private int[] score = new int[3];

	public Grade(int kor, int eng, int math) {
		score[0] = kor;
		score[1] = eng;
		score[2] = math;
	}

	public int getSum() {
		return score[0] + score[1] + score[2];
	}

	public double getAvg() {
		return getSum() / 3.0;
	}

	public char getGrade() {
		char ch = '가';
		if (getAvg() >= 90) {
			ch = '수';
		} else if (getAvg() >= 80) {
			ch = '우';
		} else if (getAvg() >= 70) {
			ch = '미';
		} else if (getAvg() >= 60) {
			ch = '양';
		} else {
			ch = '가';
		}
		return ch;
	}

	public void show() {
		System.out.println("총점 : " + getSum());
		System.out.println("평균 : " + getAvg());
		System.out.println("성적 : " + getGrade() + "입니다");
	}

}

public class JavaTest {

	public static void main(String[] args) {
		int kor, eng, math;
		Scanner sc = new Scanner(System.in);
		
		while(true) {
			System.out.print("국어 : ");
			kor = sc.nextInt();
			System.out.print("영어 : ");
			eng = sc.nextInt();
			System.out.print("수학 : ");
			math = sc.nextInt();

			Grade a = new Grade(kor, eng, math);
			a.show();
			
			System.out.println("계속 하시겠습니까? : ");
			String yn = sc.next();
			//if(yn.equals("n") || yn.equals("N") || yn.equals("no")) {play = false;}
			
			if(yn.equals("y") || yn.equals("yes")) {continue;}
			else {break;}
			
		}
		System.out.println("종료합니다");

	}

}

3-2. java 확장자를 가진 파일 이름 구하기

import java.util.Scanner;

public class JavaTest {

	public static void main(String[] args) {
		String filename;
		boolean play = true;
		Scanner sc = new Scanner(System.in);

		while (play) {

			System.out.println("파일명 입력 : ");
			filename = sc.next();

			int[] arr = new int[filename.length()];
			int temp = 0;

			for (int i = 0; i < filename.length(); i++) {
				arr[i] = filename.charAt(i);
				if (arr[i] == '.') {
					temp = i;
					break;
				}
			}

			String name = filename.substring(0, temp);
			System.out.println("파일 이름은 " + name + ", 확장자는 java입니다");

			System.out.println("계속 하시겠습니까? : ");
			String yn = sc.next();
			if (yn.equals("n") || yn.equals("no")) {
				play = false;
			}
		}
		System.out.println("종료합니다");

	}

}

3-3. 파일 이름과 확장자 분리

import java.util.Scanner;

public class JavaTest {

	public static void main(String[] args) {
		String filename;
		boolean play = true;
		Scanner sc = new Scanner(System.in);

		while (play) {

			System.out.println("파일명 입력 : ");
			filename = sc.next();

			int[] arr = new int[filename.length()];
			int temp = 0;

			for (int i = 0; i < filename.length(); i++) {
				arr[i] = filename.charAt(i);
				if (arr[i] == '.') {
					temp = i;
					break;
				}
			}

			String name = filename.substring(0, temp);
			
			String aaa = filename.substring(temp+1);
			System.out.println("파일 이름은 " + name + ", 확장자는 " + aaa + "입니다");

			System.out.println("계속 하시겠습니까? : ");
			String yn = sc.next();
			if (yn.equals("n") || yn.equals("no")) {
				play = false;
			}
		}
		System.out.println("종료합니다");

	}

}
profile
velog, GitHub, Notion 등에 작업물을 정리하고 있습니다.

0개의 댓글