배열 코드

sisun·2023년 4월 10일
0

백엔드 연습

목록 보기
5/6

본문 글
https://velog.io/@si9138/%EB%B0%B0%EC%97%B4

exam01 점수

public class Exam01 {

   public static void main(String[] args) {
   // 배열생성하기
      int[] hong;
      hong= new int[3];
      hong[0]=75;
      hong[1]=85;
      hong[2]=95;
   
      int[]lee;   //방법1
      lee=new int[] {100,90,80,70};
               //방법2
      int[] kang = {80,70,60,90};
               //방법3
      int kim []= {90,100,80,70};
               //방법4
      int[] park;
//      park = {100,90,80,}; =>에러가 남
      park= new int[] {100,90,80};
                 //방법5
      int[] jang = new int [] {90,85,75};
      
      //개인별로 총점 구하기
      int sum1=0, sum2=0,sum3=0,sum4=0,sum5=0,sum6=0;
      for(int i=0; i<3; i++){
         sum1 += hong[i];
      }
      for(int i=0; i<lee.length; i++){
         sum2 += lee[i];
         }
      for(int i=0; i<kang.length; i++){
         sum3 += kang[i];
         }
      for(int i=0; i<kim.length; i++){
         sum4 += kim[i];
         }
      for(int i=0; i<park.length; i++){
         sum5 += park[i];
         }
      for(int i=0; i<jang.length; i++){
         sum6 += jang[i];
         }
      System.out.println("홍길동의 총점 :"+sum1+"평균 : "+sum1/3);
      System.out.println("이동건의 총점 :"+sum2+"평균 : "+sum2/lee.length);
      System.out.println("강호동의 총점 :"+sum3+"평균 : "+sum3/kang.length);
      System.out.println("김민재의 총점 :"+sum4+"평균 : "+sum4/kim.length);
      System.out.println("박진호의 총점 :"+sum5+"평균 : "+sum5/park.length);
      System.out.println("장나라의 총점 :"+sum6+"평균 : "+sum6/jang.length);
      }
   }

exam 02 배열의 변수명

import java.util.Arrays;

public class Exam02 {

   public static void main(String[] args) {
	   int[] coding_score = {100,90,80,70,60,50};
	   
	   for(int i=0; i<coding_score.length; i++) {
		   System.out.println(coding_score[i]);
	   }
	   System.out.println("======================");
	   //Arrays. toString(배열의 변수명) => 배열을 통째로 출력할 수 있다.
	   System.out.println(Arrays.toString((coding_score)));
   }
}

exam 03 배열의 참조값

import java.util.Arrays;

public class Exam03 {

   public static void main(String[] args) {
	   //배열의 참조값 이해하기
	   int[] score = new int[5];
	   System.out.println(score); //주소값이 출력됨
	   System.out.println(Arrays.toString(score)); 
	   
	   double[] data = new double[7];
	   System.out.println(data);
	   System.out.println(Arrays.toString(data));
   }
}

exam 04 배열복사

import java.lang.reflect.Array;
import java.util.Arrays;

public class Exam04 {

   public static void main(String[] args) {
	   //배열을 복사하는 arraycopy()메소드
	   int[] ori = {0,1,2,3,4,5};
	   int[] desti = {0,10,20,30,40,50};
	   
	   System.arraycopy(ori ,1 ,desti, 2, 3);
	   //ori의 1번부터 3개를 desti의 2번부터 복사해서 바꿔라
	   System.out.println(Arrays.toString(ori));
	   System.out.println(Arrays.toString(desti));
   }
}

exam 05 문자열 (참조변수)

import java.util.Arrays;

public class Exam05 {
//배열에 배열 대입하기
   public static void main(String[] args) {
	   String s1 = "Hello";
	   String s2 = "Hello";
	   String s3 = "Java";
	   String s4 = new String("Hello"); //new는 새로운 메소드를 출력하겠다. 그래서 값이 같지 않음.
	   
	   System.out.println(s1);
	   System.out.println(s2);
	   System.out.println(s3);
	   System.out.println(s4);
	   
	   System.out.println("=======================");
	   System.out.println(s1 == s2);
	   System.out.println(s1 == s3);
	   System.out.println(s1 == s4);
	   
   }
}

exam 06

import java.util.Arrays;

public class Exam06 {

   public static void main(String[] args) {
	   int[]a = new int[3]; //a라는 정수에 3개를 담겠다.
	   a[0] = 5; 
	   System.out.println(a);
	   System.out.println(a[0]);
	   System.out.println(Arrays.toString(a));
	   
	   System.out.println("==================");
	   int[] b = a; //a를 b에 넣어버림
	   System.out.println(b);
	   System.out.println(Arrays.toString(b)); //그래서 a랑 값이 같다
	   
	   a[1]=10; //a에 1번째를 10으로 바꾸겠다.
	   System.out.println(Arrays.toString(a));
	   System.out.println(Arrays.toString(b));
	   
	   b[2]=20; 
	   System.out.println(Arrays.toString(a));
	   System.out.println(Arrays.toString(b));
	   
	   System.out.println(a==b);
   }
}

exam07 향상된 for 문

import java.util.Arrays;

public class Exam07 {

   public static void main(String[] args) {
	   //향상된 for문
	   int[] data = {1,3,5,7,9};
	   for(int x: data) { //임의의 변수이름 , 데이터이서 x를 담겠다. (전체 다)
		   System.out.println(x*3); //데이터에서 3씩 곱해진 값
	   }
	}
}

exam 08 2차원 배열

public class Exam08 {

	public static void main(String[] args) {
	      // 2차원 배열 학생 3명의 국어, 영어 점수.
          //[][] 행은 두개

	      int[][] scores = new int[3][2];// 크기가 3인 1차원 배열을 2개 만들기. 
          //3개인 행이 생기고 2개인 열이 생겨서 세로3 가로2인 행거열이 생김 

	      String[] name = { "홍길동", "김철수", "이영희" };

	      // 홍길동의 점수

	      scores[0][0] = 80; //행이 0이고 열이 0이라는 뜻
	      scores[0][1] = 90; //행이 0이고 열이 1이라는 뜻
	      // 김철수의 점수
	      scores[1][0] = 70;
	      scores[1][1] = 90;
	      // 이영희의 점수
	      scores[2][0] = 60;
	      scores[2][1] = 90;

	      System.out.println("scores.lenth : " + scores.length);
	      System.out.println("scores.lenth[0] : " + scores[0].length);
	      System.out.println("scores.lenth[1] : " + scores[1].length);
	      System.out.println("scores.lenth[2] : " + scores[2].length);

	      // 2차원 배열의 총점과 평균점수 구하기

	      for (int i = 0; i < scores.length; i++) { //1이 2보다 작을 때 조건 맞아서 밑에 for문으로 들어감
	         int sum = 0; //여기부터 초기화 시작
	         int avg = 0;

	         // 학생 1명의 총점과 평균 구하기.
	         for (int j = 0; j < scores[i].length; j++) {
	            sum += scores[i][j];

	         }
	         avg = sum / scores[i].length; //2로 나눔

	         System.out.printf("%s, 총점=%d, 평균=%d\n", name[i], sum, avg);

	      }
		   }
	   }

import java.util.Arrays;
import java.util.Scanner;

public class Exam09 {

	public static void main(String[] args) {
	      //5명의 학생의 점수를 입력받고 총점과 평균 구하기
		Scanner sc = new Scanner(System.in);
				
		//선언
		int[] students = new int[5];
		int sum = 0;
		
		//입력
		for(int i=0; i<students.length; i++) {
			System.out.println((i+1)+"번 학생의 점수를 입력하세요: ");
			students[i] = sc.nextInt();
		}
		//System.out.println(Arrays.toString(students));
	  // 점수만 출력
		
		//연산
		for(int i=0; i<students.length; i++) {
			sum += students[i];
            
           //향상된 for문 (둘 중 하나만 사용)
          // for(int score: students) {
	     // sum += score;
		}
		}
		//출력
		System.out.println("총점 : "+sum+", 평균"+sum/students.length);
	}
}

import java.util.Arrays;
import java.util.Scanner;

public class Exam10 {

	public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	
	int[]score = new int [5];
	System.out.println(Arrays.toString(score));
	int[] rank = null; //int[] null; 아무것도 없는것을 넣겠다.
	rank = new int[5];
	System.out.println(Arrays.toString(rank));
	
	//각 학생의 점수를 입력
	for(int i=0; i<score.length; i++) {
		System.out.println((i+1)+"번 점수를 입력 : ");
		score[i] = sc.nextInt();
		rank[i] = 1;
	}
	System.out.println("***결과***");
	
	//등수구하기
	for(int i=0; i<score.length; i++) { //기준값
		for(int j=0; j<score.length; j++) { //비굣값
			if(score[i] < score[j]) rank[i] += 1; 
			//비교해서 해야하므로 i번째 점수에 j를 다 비교해서 rank 산출 
		}
		System.out.println(score[i]+"점: "+rank[i]+"등");
	}

import java.util.Arrays;
import java.util.Scanner;

public class Exam11 {
	
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      //선언
      int[] months= {31,28,31,30,31,30,31,31,30,31,30,31};
      int year=0, month=0, day=0;
      int sum =0;
      
      //입력
      System.out.println("**일수 구하기**");
      System.out.print("년도 : ");
      year=sc.nextInt();
      System.out.print("월 : ");
      month=sc.nextInt();
      System.out.print("일 : ");
      day=sc.nextInt();
      
      //사용자가 입력한 년도가 윤년인지 평년인지 검사
      if((year%4==0)&&(year%100 !=0)||(year%400==0)) {
         months[1]=29;
      }
      //1월~입력받은 전의 달까지의 합
      for(int i=0;(i<month-1);i++) {
         sum+= months[i];
      }
      //입력받은 해당 월의 일수 최종적으로 더 더하기
      sum+= day;
      //출력
      System.out.printf("1월1일부터 %d월%d일까지의 총 일수의 합은 %d일 입니다",month,day,sum);
   }
}


1. 2번은 틀린 방법

int[] array;
array = {1,2,3,} =>에러남
array = new int[] {1,2,3}
  1. 3번
    배열의 초기값으로 정수는 0, 실수는 0.0 혹은 0.0f boolean은 false, 참조 타입 배열항목의 기본 초기값을 null(주소값을 모른다(없다)는 의미)

  2. 3,5

package siseonmi3;

import java.util.Arrays;
import java.util.Scanner;

public class Exam12_Review01 {
//3명 학생의 국,영,수 점수를 입력받아 총점, 평균, 학점 구하기
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      
      //선언
      final int NUM = 3; // 학생수
      String[] name =new String[NUM]; //학생명
      String[] subject = {"국어","영어","수학"}; //과목
      int[][] jumsu = new int[NUM][3]; //학생들의 과목별 점수
      int[] tot = new int[NUM]; //학생들의 총점
      double[] avg = new double[NUM]; //학생들의 평균
      char[] grade = new char[NUM]; //학생들의 등급
      
      //2중 for문을 이용해서 이름 입력받으면서 국,영,수 점수를 입력받기
      for(int i=0; i<name.length; i++) { //학생수만큼 반복
         System.out.println("이름 : ");
         name[i] = sc.next();
         
         for(int j=0; j<subject.length; j++) {
            System.out.printf("%s : ", subject[j]);
            jumsu[i][j] = sc.nextInt();
            tot[i] += jumsu[i][j];
         }
         avg[i] = (double)tot[i]/subject.length;
//         System.out.println("학생별 평균 점수 : " +Arrays.toString(avg));
         
         //등급 매기기
         switch((int)avg[i]/10) {
         case 10:
         case 9: grade[i] = 'A'; break;
         case 8: grade[i] = 'B'; break;
         case 7: grade[i] = 'C'; break;
         case 6: grade[i] = 'D'; break;
         default: grade[i] = 'F'; break;
         }
      }//for문의 끝태그
      
      //출력
      System.out.printf("이름\t국어\t영어\t수학\t총점\t평균\t학점\n");
      System.out.println("------------------------------------------------");
      //각 학생별로 데이터 출력하기 for문
      for(int i = 0; i<name.length; i++) {
         System.out.printf("%s\t%3d\t%3d\t%3d\t%3d\t%.2f\t%c\n", name[i], jumsu[i][0],jumsu[i][1],jumsu[i][2],tot[i],avg[i],grade[i]);
      }
   }
}


숙제

package siseonmi3;

import java.util.Arrays;
import java.util.Scanner;

public class Exam12_Review02 {
//5개의 주차 공간이 있는 주차장의 주차 시스템
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      
      //선언
      boolean[] car = new boolean[5]; //true:주차, false:비었음
      int select = 0; //선택한 메뉴를 저장하는 변수
      int position = 0; //위치값 저장
      
      //주차 관리 프로그램 출력
      
      //프로그램 종료코드
      
      //select에 담긴 값에 따른 로직 구현
   }
}

package siseonmi3;

import java.util.Arrays;
import java.util.Scanner;

public class Exam12_Review02 {
//5개의 주차 공간이 있는 주차장의 주차 시스템
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      
      //선언
      boolean[] car = new boolean[5]; //true:주차, false:비었음
      //boolean은 기본적으로 false가 입력되어있음
      int select = 0; //선택한 메뉴를 저장하는 변수
      int position = 0; //위치값 저장
      
      //주차 관리 프로그램 출력
      while(true) {
       	System.out.println("주차관리 프로그램");
      System.out.println("************");
      System.out.println("\t 1.입차");
      System.out.println("\t 2.출차");
      System.out.println("\t 3.리스트");
      System.out.println("\t 4.종료");
      System.out.println("************");
      System.out.println("메뉴를 선택하세요: ");
      select = sc.nextInt();
       	
      //프로그램 종료코드를 먼저 하고 확인하기
      if(select == 4) {
    	  System.out.println("프로그램을 종료합니다.");
    	  break;
      }
      //select에 담긴 값에 따른 로직 구현
      switch(select) {
      case 1:
    	  System.out.println("위치 입력[1~5] : ");
    	  position = sc.nextInt();
    	  if(car[position-1]) {//true:주차된 차가 존재
    		  System.out.println(position+"위치에 이미 주차되어 있습니다");
    	  }else {
    		  car[position-1] = true; //주차가 되었다고 값 변경
    		  System.out.println(position+"위치에 입차/주차 되었습니다.");
    	  }
    	  break;
      case 2:
    	  System.out.println("위치 입력 [1~5] : ");
    	  position = sc.nextInt();
    	  if (car [position-1]) { //차가 빠졌을 때
    		  car[position-1] = false; //출차후에는 다시 주차된 차가 없다고 변경
    		  System.out.println(position + "위치의 차를 출차하였습니다. ");
    	  }else {
    		  System.out.println(position+"위치에 주차되어 있지 않습니다");
    	  }  
    	  break;
      case 3:
    	  System.out.println();
    	  System.out.println("---주차 리스트---");
    	  for(int i = 0; i < car.length; i++) {
    		  System.out.println((i+1)+"번 위치: "+car[i]);
    	  }
    	  break;
    	  }
      System.out.println();
      }
   }
}
profile
풀스택 국비수강중

0개의 댓글