자바

 

Student

package com.gradebook;

public class Student {

	private int studentId;  //학번
	private int score; //성적
	private int week; //주차
	private double average; //평균
	private double sum; //합계
	private int count;// 과목 수
	
	public int getStudentId() {
		return studentId;
	}
	public void setStudentId(int studentId) {
		this.studentId = studentId;
	}
	public int getScore() {
		return score;
	}
	public void setScore(int score) {
		this.score = score;
	}
	public int getWeek() {
		return week;
	}
	public void setWeek(int week) {
		this.week = week;
	}
		
	public double getAverage() {
		return average;
	}
	public void setAverage(double average) {
		this.average = average;
	}
	public double getSum() {
		return sum;
	}
	public void setSum(double sum) {
		this.sum = sum;
	}
	
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	
	
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + studentId;
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (studentId != other.studentId)
			return false;
		return true;
	}
	
	@Override
	public String toString() {
		return "Student [studentId=" + studentId + ", score=" + score + ", week=" + week + ", average=" + average
				+ ", sum=" + sum + ", count=" + count + "]";
	}
	


	
	
}

 

 

GradeBook

package com.gradebook;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class GradeBook {

	//List 학생을 담을 객체 생성
	List<Student> studentList;
	Scanner scanner;
	
	private void gradeBook(){
		//List<Student> 객체를 생성한다.
		studentList=new ArrayList<>();
		
		scanner=new Scanner(System.in);
		
		StringBuffer sb=new StringBuffer();
		sb.append("성적 입력 / 수정 : u 학번(int) 성적(int) 주차(int)\n");
		sb.append("총 인원 출력 : n \n");
	    sb.append("평균 / 표준 편찬 출력 : s 주차(int) \n");
	    sb.append("1등 학생 출력 : t \n");
	    sb.append("꼴등 학생 출력 : l \n");
	    sb.append("종료 : q \n");
		System.out.println(sb.toString());
 
		while(true){
		
			String str =scanner.next();	
			
			while(true){
				
				System.out.print("command > ");	
				String firstInput =scanner.next();	
				
				//첫번째 입력이 u 이면 성적 입력 및 수정
				if(firstInput.equals("u")){
					try {	
						uInput();	
					} catch (Exception e) {
						System.out.println("잘못 입력 하였습니다. 다시 선택하세요.");
						break;
					}
				}		
				
				//첫번째 문자가 n 이면 총 인원을 구한다.
				if(firstInput.equals("n")){
					System.out.println(nInput().size());
				}
				
				
				//첫번째 문자가 s 이면 해당 주차의 점수의 평균과 표준편차를 출력한다.
				//해당 주차에 점수가 없는 학생은 무시한다.
				if(firstInput.equals("s")){
					try {
						sInput();
					} catch (Exception e) {
						System.out.println("잘못 입력 하였습니다. 다시 선택하세요.");
						break;
					}
				}
		
				//성적의 평균이 가장 높은 학생의 학번을 출력한다
				if(firstInput.equals("t")){
					tInput();
				}
				
				//성적의 평균이 가장 낮은 학생의 학번을 출력한다
				if(firstInput.equals("l")){		
					lInput();
				}
				
				//첫번째 문자가 q 이면 종료된다.
				if(firstInput.equals("q")){			
					break;
				}
				
				
				//첫번째 문자가 a 전체 데이터를 출력한다.
				if(firstInput.equals("a")){	
					System.out.println("전체 출력");		
					for(Student  st : studentList){
						System.out.println(st.toString());
					}
				}
			}
			
			
			System.out.println("계속하려면 아무키나 누르십시오...");	
		}
	}
	
	
	
	//첫번째 입력이u 경우 - 성적 입력 및 수정 하는 메소드
	private void uInput() throws Exception{
		String id =scanner.next(); 
		String score =scanner.next();
		String week =scanner.next();
		
		// isNew 는 새롭게 넣을지 또는 수정할지 결정한다. 
		boolean isUpdate=false;
		//기존 데이터를 수정 할 경우 해당 List 의 번호를 가져온다.
		int getListId=0;
							
			//기존의 데이터가 존재하면 if 문으로 들어간다.
			if(studentList.size()>0){			
				for(int i=0; i<studentList.size(); i++){					
					
					
					//동일한 학번이 존재하는지 찾는다.
					//System.out.println("studentList.get(i).getStudentId()" +studentList.get(i).getStudentId());
					if(Integer.parseInt(id)==studentList.get(i).getStudentId()){
						//System.out.println("같은 학번이다.");
						// 해당 주차가 존재하는지 확인한다.
						
						if(Integer.parseInt(week)==studentList.get(i).getWeek()){
							//System.out.println("동일한 주차이다");
							//동일한 학번에 동일한 해당 주차인 경우 수정을 한다.
							//해당 학번을 가진 학생의 해당 주차 점수를 해당 점수로 갱신한다
							isUpdate=true;
							getListId=i;
						   // System.out.println(" 1 isUpdate :" +isUpdate + "  번호 :"+ getListId);
						    break;
						}else{
							//동일한 학번이지만 주차가 다른 경우는 Student 객체생성 후 새로 추가한다.	
						   //	System.out.println("2 isUpdate :" +isUpdate);
						}						
					}else{
						//동일한 학번이 아닌경우에는 Student 객체생성 후 새로 추가한다.
						//System.out.println("3 isUpdate :" +isUpdate);
					}
				}
				
			}
		
			if(isUpdate){					
				//해당 학번을 가진 학생의 해당 주차 점수를 해당 점수로 갱신한다.
				//System.out.println("업데이트 ");
				for(int i=0; i<studentList.size(); i++){
					//List 의 수정할 해당 객체를 찾는다. 
					if(i==getListId){
						//점수를 갱신한다.
						studentList.get(i).setScore(Integer.parseInt(score));
						break;
					}
				}
			}else{	
				//System.out.println("student 생성");
				gradeInput(id, score, week);		
			}
				
			isUpdate=false;
	}
	
	
	//성적 입력 메소드
	private void gradeInput(String id, String score, String week) {
		//학번 , 점수, 주차 를 저장할 DTO  Student 개체를 생성한다. 
		Student student=new Student();	
		student.setStudentId(Integer.parseInt(id));
		student.setScore(Integer.parseInt(score));
		student.setWeek(Integer.parseInt(week));					
		studentList.add(student);
	}
	
	
	//n 키 입력시 - 총 인원을 구하는 메소드 
	//반환 값은 중복이 제거된 학번 목록이다.
	private List<Student> nInput(){
		//학번을 기준으로 중복 제거를 위한 List 객체를 생성한다.
		List<Student> resultList=new ArrayList<>();
		
		List<Integer> id=new ArrayList<>();
		
		//List<Student> 객체에 담긴 객체를 반복문을 돌린다.
		for(Student st : studentList){
			
			//만약에 resultList 객체에 동일한 학번이 존재하지 않으면 
			if(!id.contains(st.getStudentId())){		
				// resultList 에 학번을 추가한다.
				Student student=new Student();
				student.setStudentId(st.getStudentId());
				
				id.add(st.getStudentId());
				resultList.add(student);
				
			}	
		}
		
		//중복이 제거 된 resultList 사이즈는 곧 학생수가 된다.
		return resultList;
		
	}
	
	
	// s 키 입력시 - 해당 주차의 점수의 평균과 표준편차를 출력하는 메소드
	private void sInput() throws Exception{
		//주차 입력
		String week =scanner.next();  
		
		//평균
		double sum=0.0;
		double diff;
		double average=0.0;
		
		//표준편차를 구하기 위한 list
		List<Double> doubleScore= new ArrayList<>();
		
		for(int i=0; i<studentList.size(); i++){
			
			//주차가 같을 경우
			if(Integer.parseInt(week)==studentList.get(i).getWeek()){
				//합산한다.
				sum +=studentList.get(i).getScore();
				doubleScore.add((double)studentList.get(i).getScore());
			}
		}
		
		//평균 sum / 학생수
		average = sum/doubleScore.size();
		
		//소수점 5째자리 이하 반올림
		System.out.println(week +"주차 평균 : " + (int)(average* 100000 + 0.5)/100000.0);
		
		//표준 편차 구하기 - 공식 적용
		String sqrtString="";
		sum=0.0;
		if (doubleScore.size() < 2)  sqrtString="NaN";		
		for (int i = 0; i < doubleScore.size(); i++) {
		      diff = doubleScore.get(i) - average;
		      sum += diff * diff;
		}
		
		double sqrt = Math.sqrt(sum / (doubleScore.size() - 0));
		//소수점 5째자리 이하 반올림
		sqrtString=String.valueOf(  (int)(sqrt* 100000 + 0.5)/100000.0  );
		System.out.println("표준편차 : " +sqrtString);
		
	}
	

	// t 키 입력시 - 성적의 평균이 가장 높은 학생의 학번을 출력한다.
	private void tInput(){
		List<Student> stL=	averAgeList();
		//성적의 평균이 가장 높은 학생의 학번을 출력
	
		if(stL.size()==0){
			System.out.println("데이터를 입력하세요");
		}else{
			List<Double> d =new ArrayList<>(); 
			for(int i=0; i<stL.size(); i++){
				d.add(stL.get(i).getAverage());
			}
			double max=Collections.max(d);
			
			Integer studentId=null;
			for(int i=0; i<stL.size(); i++){
				//평균이 최대값이 같으면 해당 학번을 가져온다.
				if(stL.get(i).getAverage()==max){		
					studentId =stL.get(i).getStudentId();
					break;
				}
			}
			System.out.println(studentId);
		}
			
	}

	// l 키 입력시 - 성적의 평균이 가장 낮은 학생의 학번을 출력한다.
	private void lInput(){
		List<Student> stL=	averAgeList();
		if(stL.size()==0){
			System.out.println("데이터를 입력하세요");
		}else{
			
			List<Double> d =new ArrayList<>(); 
			for(int i=0; i<stL.size(); i++){
				d.add(stL.get(i).getAverage());
			}
			
			double min=Collections.min(d);
			
			Integer studentId=null;
			
			for(int i=0; i<stL.size(); i++){
				//평균이 최소값인 같으면 해당 학번을 가져온다.
				if(stL.get(i).getAverage()==min){		
					studentId =stL.get(i).getStudentId();
					break;
				}
			}
			
			System.out.println(studentId);
		}
		
	}

	
	//학생의 평균과 합계 계산
	private List<Student> averAgeList(){
		//1.학생의 합계구하기
		//nInput() 중복이 제거된 학번 sum 
		List<Student> stL=nInput();		
		for(int i=0; i<stL.size(); i++){
			
			for(int j=0; j<studentList.size(); j++){	
				//만약 nInput 의 i 번째 학번과 같으면 sum 누적시킨다.
				if(stL.get(i).getStudentId()==studentList.get(j).getStudentId()){
					//합계
					stL.get(i).setSum( stL.get(i).getSum()+ studentList.get(j).getScore());
					
					//과목수 누적
					stL.get(i).setCount(stL.get(i).getCount()+ 1);
				}
				
			}
		}
		
		//2.평균 구하기
		for(Student s: stL){
			s.setAverage(s.getSum()/s.getCount());
			//System.out.println(s.toString());
		}
		return stL;
	}
	
	
	
	
	public static void main(String[] args) {
		GradeBook gradeBook=new GradeBook();
		gradeBook.gradeBook();
		
	}
	
	

	
	
}

 

test.txt

 

u 22162012 10 1
u 22162012 9 2
u 22162012 8 3
u 22162012 7 4
u 22162012 6 5
u 20101587 1 1
u 20101587 2 2
u 20101587 3 3
u 20101587 4 4
u 20101587 5 5
u 20101587 6 6
u 11111111 1 1
u 11111111 1 1
u 11111111 3 3
u 11111111 3 3

 

 

콘솔

 

 

 

 

 

 

 

about author

PHRASE

Level 60  라이트

아무리 가까운 사람일지라도 어찌 나의 짐을 짊어지려 하겠는가. -코란

댓글 ( 4)

댓글 남기기

작성

자바 목록    more