My footsteps

성적관리 함수화 본문

국비수업/수업정리

성적관리 함수화

밀김 2023. 3. 9. 21:34
728x90

 

 

 

 

 

 

package newlec;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;
public class G5Program2 {
	
	
	public static int inputMenu(int menu) {
		//성적로드
		//저장되어있는 객체의 값들을 불러온다???함수호출?
		//메뉴입력한거 저장하기
		//객체를 만들어서 객체에 값을 저장하고 작동하게 
		//반환값이 있느냐? 있지 menu
		System.out.println("┌────────────────────────┐");
		System.out.println("│          성적관리         │");
		System.out.println("└────────────────────────┘");
		
		Scanner sc = new Scanner(System.in);
		System.out.println("번호를 입력해 주세요");
		System.out.println("1. 성적 입력");
		System.out.println("2. 성적 출력");
		System.out.println("3. 성적 저장");
		System.out.println("4. 성적 로드");
		System.out.println("5. 종료");
		System.out.print("번호를 입력해주세요 >");
		
		menu = sc.nextInt();
		return menu;
	}
	
	
	
	
	
	
	public static Exam[] inputExams(Index index,Exam[] exams) {
		//성적입력
		//성적을 입력 받고..성적이 저장 되게
		System.out.println("┌──────────────┐");
		System.out.println("┃    성적입력    ┃");
		System.out.println("└──────────────┘");

		Scanner sc = new Scanner(System.in);

		while (true) {
			Exam exam = new Exam(); // exam 객체 생성 접근 쌉가능
			if (index.idx == exams.length) { // 공간이 충분한지, 또는 여유공간이 있는지
				Exam[] temp = new Exam[exams.length + 3];
				for (int i = 0; i < exams.length; i++)
					temp[i] = exams[i];//exams배열을 넓은 temp배열에 옮긴다
					exams = temp;//temp를 exams로 바꿔준다
			}


			System.out.print("국어 성적을 입력하세요 : ");
			exam.kor = sc.nextInt();
			System.out.print("영어 성적을 입력하세요 : ");
			exam.eng = sc.nextInt();
			System.out.print("수학 성적을 입력하세요 : ");
			exam.math = sc.nextInt();

			exams[index.idx] = exam;//exams에 0번째와 연결된다
			index.idx++;//인덱스는 값변수니까 저장이안된다
	
			System.out.println("그만하시겠습니까? 1. 예 2. 아니오");
			int subMenu = sc.nextInt();
			if (subMenu == 1)
				break;
		}
		return exams;
	}
	
	
	
	

	static Exam[] scorePrint(Exam[] exams, Index index) {
		for (int i = 0; i < index.idx ; i++) {//인덱스객체를 생성해놓은상태라,연결이 되어있어서 값이 초기화되지않고 그대로 1로 유지되어 내려온다
			Exam exam = exams[i];

			int kor = exam.kor;
			int eng = exam.eng;
			int math = exam.math;

			System.out.printf("국어 %d: %3d 점 \n", i + 1, kor);
			System.out.printf("영어 %d: %3d 점 \n", i + 1, eng);
			System.out.printf("수학 %d: %3d 점 \n", i + 1, math);
			System.out.println("----------------");

		}
		return exams;
	}

	
	
	
	private static void saveExams(Index index,Exam[] exams,String fileName) throws FileNotFoundException {
		//저장
		//객체에 값이 저장되게?? 함수를 통해 전달한다?
		FileOutputStream fos = new FileOutputStream(fileName);
		PrintStream fout = new PrintStream(fos);

		for (int i = 0; i < index.idx; i++) {
			Exam exam = exams[i];
			int kor = exam.kor;
			int eng = exam.eng;
			int math = exam.math;
			fout.printf("%d %d %d\n", kor, eng, math);
//			if (i < index.idx - 1) { //줄바꿈
//				fout.println();
//			}
		}
	}
	
	
	
	private static void loadExams(Index index,Exam[] exams,String fileName) throws IOException {
		//메뉴입력한거 로드하기
		FileInputStream fis = new FileInputStream(fileName);

		Scanner fscan = new Scanner(fis);

		for (int i = 0; i < index.idx; i++) {

			String scoreLine = fscan.nextLine();

			String[] scoreTokens = scoreLine.split(" ");

			exams[i].kor = Integer.parseInt(scoreTokens[0]);
			exams[i].eng = Integer.parseInt(scoreTokens[1]);
			exams[i].math = Integer.parseInt(scoreTokens[2]);

		}

		scorePrint(exams, index);
		//값을 잘라서 담고 출력해야하니까 출력함수를  다시 호출
		
		fscan.close();
		fis.close();

	}


	
	
	
	public static void main(String[] args) throws IOException {

		Exam[] exams = new Exam[5];
		
		Index index = new Index();

		String fileName = "res/exam.txt";

		END: while (true) {
			int menu = 0;
			menu = inputMenu(menu);//함수로 대체
			//메뉴를 입력받고
		
			switch (menu) {
			case 1: // 입력은 사용자에게 하나씩 받는다.
				//성적을 입력받고
				exams = inputExams(index,exams);
				break;

			case 2: // 출력은 일괄적으로 해준다. for문 사용.
				//성적을 출력하고
				System.out.println("┌──────────────┐");
				System.out.println("┃    성적출력    ┃");
				System.out.println("└──────────────┘");
				
				exams = scorePrint(exams, index);
				break;
				
			case 3:// 성적 저장
				saveExams(index, exams, fileName);//void
				break;
			case 4:// 성적 로드
				loadExams(index, exams, fileName);
				break;
			case 5:
				System.out.println("성적 입력 프로그램을 종료합니다. 안녕~");
				break END;
			default:
				System.out.println("잘못된 입력입니다.");
				break;
			}

		}
	}//메인 메소드

}//main class


//인덱스 클래스 만들고 > 객체 만들어서 > 공간을 계속 늘리고있는 exam.lenght에 연결?참조? 되면서 index도 계속 증가하게 된다

class Index{
	int idx;
}

 

 

- 인덱스 객체를 메인에 또 만들어준 이유: 함수내에서만 인덱스가 증가한다던가 함수 안에서 인덱스 객체가 생성된다면 인덱스가 증가하다가 함수가 끝나면 종료되기 때문에 그 문제를 해결하고자 객체를 따로 만들어 exam.length == index.idx해준다음에 같이 증가할수 있도록 연결?해줌. index가 값변수가 아니라 참조변수가 되게!!!!

 

 

 


<멘토쌤 함수 특강..>

 

package newlec;

public class CatFactory {
   public static void main(String[]args) {


      Cat cat1 = new Cat();
      cat1.age = 1;
      Cat cat2 = new Cat();
      cat2.age = 1;
      Cat cat3= new Cat();
      cat3.age = 1;
      Cat cat4= new Cat();
      cat4.age = 1;
      Cat cat5= new Cat();
      cat5.age = 1;

      Cat cat6 = makeCat(4);
      System.out.println(cat6.age);


   }   
   static Cat makeCat(int age) {
      Cat cat = new Cat();
      cat.age = age;

      return cat;

   }


}
class Cat{

   int age;
}

 

package newlec;

import java.util.Random;

public class Count {

   public static void main(String[] args) {



      int result = add(1,3);

      int result1 = multiple(2,3,4);

   
      //         int num1 = rand.nextInt(6);
      //         int num2 = rand.nextInt(6);
      //         int num3 = rand.nextInt(6);
      //         int num4 = rand.nextInt(6);
      //         int num5 = rand.nextInt(6);
      //         int num6 = rand.nextInt(6);
      
      int[] lottos1 = createLottoNums(10);
      int[] lottos2 = createLottoNums(10);


   }

   static int add (int a , int b) {
      //  int result = a+b ; 
      return a+b; //result; 

   }
   static int multiple(int a,int b , int c) {

      return a*b*c;
   }

   static int[] createLottoNums(int size) {
      Random rand = new Random();
      int[] num = new int[size];
      for(int i = 0 ; i<size ; i++)
         num[i] = rand.nextInt(45)+1;
      
      return num;
   }
}

 

package newlec;

import java.util.Random;

public class LottoPrj {

   public static void main(String[] args) {

      // 크기가 6인 정수형 배열을 만들고  , 거기에 랜덤 번호 채우기

      
      int[] lottos = generateLottoNums();
      printLottoNums(lottos);
      // 출력만하니까!!!!

      //1~45 만드는 함수 만들어주세요



   }

   static int makeRandomNums(int x) {

      Random rand = new Random();

      return rand.nextInt(x);

   }

   static void printLottoNums(int[] nums) {
      for(int i = 0; i<nums.length;i++)
         System.out.println(nums[i]);

   }
   
   static int[] generateLottoNums() {
      int[] nums = new int[6];
      for(int i = 0;i<nums.length;i++) 
         nums[i] = makeRandomNums(45)+1;
      
      return nums;
   }

}

 

 

 

 

 

 

 

 

 

728x90

'국비수업 > 수업정리' 카테고리의 다른 글

개체 간의 메세지 교환을 뽑아내보기  (0) 2023.03.10
객체지향  (0) 2023.03.10
함수 심화 문제  (0) 2023.03.08
배열 이주하기 / 함수  (0) 2023.03.07
데이터 구조화 / 구조체 배열  (0) 2023.03.06