동일한 데이터 타입의 여러 값을 담을 수 있는 자료구조로, 하나의 변수명으로 여러 개의 값을 관리
특징
1. 인덱스(Index): 배열의 각 요소는 인덱스를 가지며, 인덱스는 0부터 시작
2. 크기 고정: 배열은 생성할 때 크기가 결정되며, 크기를 동적으로 변경할 수 없음.
3. 동일한 데이터 타입: 배열은 동일한 데이터 타입의 요소들로 이루어짐.
4. 메모리 구조: 연속된 메모리 공간에 요소들이 저장되므로 특정 인덱스에 빠르게 접근
5. 반복문 활용: 배열의 요소에 접근하거나 값을 변경할 때 주로 반복문을 사용
1차원배열
// 선언과 초기화
int[] arr1 = new int[5];
// 또는
int[] arr1 = {1, 2, 3, 4, 5};
1차원배열
// 선언과 초기화
int[] arr1 = new int[5];
// 또는
int[] arr1 = {1, 2, 3, 4, 5};
2차원배열
// 선언과 초기화
int[][] arr2 = new int[3][4];
// 또는
int[][] arr2 = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
3차원배열
// 선언과 초기화
int[][][] arr3 = new int[2][3][4];
// 또는
int[][][] arr3 = {
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
},
{
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24}
}
};
예측할 수 없는 무작위의 수를 의미하며, java.util.Random 클래스나 Math.random() 메서드를 통해 난수를 생성
java.util.Random 클래스 사용
import java.util.Random;
public class RandomExample {
public static void main(String[] args) {
// Random 클래스 인스턴스 생성
Random random = new Random();
// 정수형 난수 생성 (0 이상, 지정한 수 미만)
int randomInt = random.nextInt(10); // 0부터 9까지의 난수
// 실수형 난수 생성 (0.0 이상, 1.0 미만)
double randomDouble = random.nextDouble();
System.out.println("Random Integer: " + randomInt);
System.out.println("Random Double: " + randomDouble);
}
}
Math.random() 메서드 사용
public class MathRandomExample {
public static void main(String[] args) {
// 실수형 난수 생성 (0.0 이상, 1.0 미만)
double randomValue = Math.random();
System.out.println("Random Value: " + randomValue);
}
}
주의사항
1. Random 클래스는 시드(seed) 값을 기반으로 난수를 생성하며, 동일한 시드로 생성된 인스턴스는 같은 난수를 생성.
2. Math.random()은 내부적으로 Random 클래스를 사용하며, 0.0 이상 1.0 미만의 난수를 반환.
3. 난수 생성 시 필요에 따라 범위를 조절하여 사용.
4. 안전한 난수 생성을 위해 보안용으로 사용하는 java.security.SecureRandom 클래스도 존재.
String 입력:
next() 메서드는 공백을 기준으로 한 단어를 입력 받는다.
따라서 sc.next()로 입력 받으면 공백을 기준으로 첫 번째 단어만을 읽는다.
nextLine() 메서드는 공백을 포함한 한 줄 전체를 입력 받는다.
따라서 sc.nextLine()으로 입력 받으면 한 줄 전체를 읽는다.
** 혼합입력
String name = sc.nextLine();
int su = sc.nextInt();
System.out.println(su + "," + name); // 이상없음
int su2 = sc.nextInt();
String name2 = sc.nextLine();
System.out.println(su2 + "," + name2); //
// nextInt()는 정수를 받고 엔터키(\n)를 버퍼에 남겨둬,
nextLine()이 실행되면 엔터키를 읽고 문자열 입력이 시작되어 빈문자열이 저장.
이때 nextLine()이 남겨둔 엔터키를 읽어오기 때문에 의도하지 않은 동작이 발생
이를 해결하기 위해 nextInt() 이후에 sc.nextLine()을 추가하여 엔터키를 소비하도록 해야함.
문자열 비교
equals(Object obj)
두 문자열이 내용이 같은지 비교.
대소문자를 구분.
String str1 = "Hello";
String str2 = "hello";
System.out.println(str1.equals(str2)); // false
equalsIgnoreCase(String anotherString)
두 문자열이 내용이 같은지 비교.
대소문자를 무시.
String str1 = "Hello";
String str2 = "hello";
System.out.println(str1.equalsIgnoreCase(str2)); // true
compareTo(String anotherString)
두 문자열을 사전 순서로 비교.
두 문자열이 같으면 0을 반환, 사전 순으로 이전이면 음수를, 이후이면 양수를 반환.
String str1 = "apple";
String str2 = "banana";
System.out.println(str1.compareTo(str2)); // 음수반환