[Java] ArrayList에 합계, 평균 저장

호빵·2024년 7월 22일

Java_문제 풀이

목록 보기
7/8

📅 공부 기간 : 07. 18(목)

활용 메소드

  • ArrayList에 저장된 객체의 개수 : source.size()
  • 배열 길이 : temp.length
  • 저장된 위치(index)에 저장된 객체 반환 : source.get(i)
  • 문자열을 정수로 변환 : Integer.parseInt()
  • ArrayList의 마지막에 객체 추가 : target.add()
  • ArrayList의 모든 요소에 대해 작업 수행 : target.forEach(action)

프로그램

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Exam_33 {

	public static void main(String[] args) {
		List<String> source = Arrays.asList(
				"홍길동 100 95 85", // source.get(i) ==> String[] ==>"100" "95" "85" => Integer.parseInt()
				"임꺽정 85 77 68",
				"전우치 88 65 74",
				"손오공 100 99 87",
				"사오정 74 58 99"
				);
		
		List<String> target = new ArrayList<>();
		// "홍길동 100 95 85 xxx xx.xx"
		
		// API : String - split(), format(), Integer - parseInt(), StringBuffer - append()
		// 		 List - get(), add()
		// 최종 출력 : forEach()
		
		for(int i = 0; i < source.size(); i++) {
			String[] temp = source.get(i).split(" ");
			String name = temp[0];
			
			int total = 0;
			double avg = 0;
			
			for (int j=1; j<temp.length; ++j)
				total += Integer.parseInt(temp[j]);
			
			avg = total / 3.0;
			
			target.add(String.format("%s %3s %3s %3s %4d %.2f", name, temp[1], temp[2], temp[3], total, avg));
		}
		
		target.forEach((s)-> System.out.println(s));
	}
	
}
profile
인류의 위대한 대화에 참여하기 위해 다양한 언어를 탐구합니다.

0개의 댓글