배열 ch5

IT/JAVA / / 2021. 5. 30. 18:05

배열이란

같은 타입의 여러 변수를 하나의 묶음으로 다루는 것을 배열이라고 한다.

 

배열의 선언과 생성 :타입[] 변수이름, 혹은 타입 변수이름 [] 으로 붙여도 둘다 가능하다.

 

int[] scores = new int [5] 
//이런식으로 scores라는 int 배열을 5칸 선언하는것이다.

배열의 요소마다 붙여진 일련번호를 index라고 하며 인덱스의 범위는 0부터 배열길이 -1 까지 이다. 처음 시작하는 배열은 무조건 0부터 시작한다는 말

 

int [] scores = new int [5] { 100, 99, 98, 97, 96}
//라면 int [0] = 100 인것이다 

 

배열은 입력이나, 출력할때 for문을 같이 쓰면 매우 유용하다.

string[] temp = new string [5];

Scanner scanner = new Scanner(System.in);

// 배열 입력
for (int i = 0; i < temp.Length; ++i)
{
	string temp[i] = scanner. nextLine();
}


// 배열 출력
for (int i = 0; i < temp.Length; ++i)
{
	System.out.println(temp[i]);
}

 

다차원 배열 선언과 대입 은 다음과 같이 한다

int[][]temp = new int [5][5] {
{ 1,2,3,4,5},
{ 1,2,3,4,5}
};

 

배열과 관련된 예제

 

1. 빙고 만들기

 

자바 스터디 팀원인 유미님의 블로그에서 캡쳐해 왔다

tip) 자바의 정석에 나오는 빙고를 활용해서 만들어도 만들 수 있다 

내가 쓴 정답은 더보기에 있다.

더보기
public class bingo {
	
	
public static void main(String[] args) {
			

	final int SIZE = 5;
	int x = 0;
	int y = 0;
	int  num = 0;
	int countOfPlay = 0;
	String [][] resultTable = {
		 {"[0,0]", "[0,1]","[0,2]","[0,3]","[0,4]"}, 
		 {"[1,0]", "[1,1]","[1,2]","[1,3]","[1,4]"},
		 {"[2,0]", "[2,1]","[2,2]","[2,3]","[2,4]"},
		 {"[3,0]", "[3,1]","[3,2]","[3,3]","[3,4]"},
		 {"[4,0]", "[4,1]","[4,2]","[4,3]","[4,4]"},
	 };
			 
	// new number create 
	 int[][] table = new int [SIZE][SIZE];
	 for (int i = 0; i < SIZE; ++i)
	 {
		 for (int j = 0; j< SIZE; ++j)
		 {
			 table[i][j] = i * SIZE + j +1;
		 }
	 }
			 
	 // number shuffle
	 for (int i = 0; i < SIZE; ++i)
	 {
		 for (int j = 0; j< SIZE; ++j)
		 {
			 x = (int)(Math.random() * SIZE);
			 y = (int)(Math.random() * SIZE);
			 int temp = table [i][j];
			 table [i][j] = table [x][y];
			 table [x][y] = temp;
		 }
	 }
			 
			  
	 while (true)
	 {
				 
		// bingo table output
		 for (int i = 0; i < SIZE; ++i)
         {
			 for (int j = 0; j< SIZE; ++j)
			 {
				System.out.print(String.format("%1$6s", resultTable[i][j]));
			 }
			 System.out.println();
		 }
			 
		 Scanner sc = new Scanner(System.in);
		 String consoleInput = sc.nextLine();
		 num = Integer.parseInt(consoleInput);
				 
		 System.out.println("1부터 25까지의 수를 입력하세요");
	 	 System.out.println("종료하려면 0을 입력하세요");

		 int countOfBingo = 0;
			 	 
		 going:
	 	 for (int i = 0; i < SIZE; ++i)
		 {
			 for (int j = 0; j< SIZE; ++j)
			 {
				 if(table[i][j] == num)
				 {
					 table[i][j] = 0;
					 resultTable[i][j] = consoleInput;
					 countOfPlay++;
					 break going;
				 }
			 }
		 }
				
	 	 //consider bingo in the table
	 	for (int i = 0; i < SIZE; ++i)
	 	{
			 	if (table [0][i] == 0 && table [1][i] == 0 && table [2][i] == 0 
                && table [3][i] == 0 && table [4][i] == 0)
				{
					countOfBingo++;
			 	}
			 			
				if (table [i][0] == 0 && table [i][1] == 0 && table [i][2] == 0 
                && table [i][3] == 0 && table [i][4] == 0)
				{
			 		countOfBingo++;
			 	}	
		}
			 	

		if(table[4][4] == 0 && table[3][3] == 0 && table[2][2] == 0 
        && table[1][1] == 0 && table[0][0] == 0)
		{
			System.out.println("왼쪽 대각선 빙고");
			countOfBingo++;
		}
		else if(table[4][0] == 0 && table[3][1] == 0 && table[2][2] == 0 
        && table[1][3] == 0 && table[0][4] == 0)
		{
			System.out.println("오른쪽 대각선 빙고");
			countOfBingo++;
		}
				
	 	System.out.printf("%d빙고%n", countOfBingo);
			 	 
		if(num == 0 || countOfPlay > 25)
		{
			System.out.println("종료되었습니다");
			break;
		}
				
			}
	
		
	}
}

 

2. 배열안 버블정렬 

int[] b = new int[] { 99, 8, 4, 6, 9 };
int temp = 0;

for (int i = 0; i < b.Length; i++)
{
    for (int j = 0; j < b.Length; j++)
    {
        if (b[i] < b[j])
        {
            temp = b[i];
            b[i] = b[j];
            b[j] = temp;
        }
     }
}

for (int i = 0; i < b.Length; i++)
{
    Console.Write(b[i] + ", ");
}
728x90
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기