ctrl + shift + o
- 같은 타입의 여러 변수를 하나의 묶음으로 다루는 것
int[] 배열이름 = new int[크기];
int 배열이름[] = new int[크기];
- index : 0 1 ... n-2 n-1
배열을 다루기 위한 참조변수 선언
방법1) 타입[] 변수이름;
int[] score;
String[] name;
타입 변수이름[];
int score[];
String name[];
-> 참조변수 score
, name
실제 저장공간 생성
✨해당 저장공간(오른쪽)의 주소를 참조변수(왼쪽)에 저장
변수이름 = new 타입[길이];
score = new int[5];
name = new String[5];
배열이름.length;
배열을 한 번 생성하면 실행 동안 크기를 바꿀 수 없다.
길이를 활용할 때
int[] arr = new int[9];
for(int i=0; i<arr.length; i++) {
//...
}
로 하자! ✨리터럴(9
)을 쓰지 말고!!
int score[] = {10, 20, 50, 33, 88};
//배열 선언, 생성, 초기화
나눠서 쓰지 말고 가능하면 한 줄로!
int score[];
score = new int[]{10, 20, 50, 33, 88};
char[]
의 출력char[] chArr = ['a', 'b', 'c', 'd'];
System.out.println(chArr);
abcd
int[] iArr = {10, 20, 30, 40};
for(int i=0; i<iArr.length; i++) {
System.out.println(iArr[i]);
}
10
20
30
40
Arrays.toString(배열이름)
사용int[] iArr = {10, 20, 30, 40};
System.out.println(Arrays.toString(iArr));
[10, 20, 30, 40]
for
문(반복문) 활용해서 sum
에 집어넣기실수인 ✨float
또는 double
✨타입의 변수average
마련하기
나눌 때 ✨✨average = sum / (float or double)arr.length
형변환 주의
public class Ex5_2 {
public static void main(String[] args) {
int sum = 0; //총합
float average = 0f; //평균, 실수로, float은 f
double average2 = 0;//요건 double, double은 d또는 생략
int[] score = {100, 88, 100, 100, 90};
for(int i=0; i<score.length; i++) {
sum += score[i];
}
System.out.println("총합 = "+sum);
average = (sum / (float)score.length); //95.6f
average2 = (sum / (double)score.length);//95.6d
//형변환 주의!!!! 둘중 아무거나 float 붙여라!!
System.out.println("평균 = "+average);
System.out.println("평균 = "+average2);
}
}
총합 = 478
평균 = 95.6
평균 = 95.6
한번에 처리할 수 있다!!
public class Ex5_3 {
public static void main(String[] args) {
int[] score = {79, 88, 33, 91, 100, 55, 95};
int max = score[0]; //초깃값은 배열의 첫번째값으로
int min = score[0];
for(int i=1; i<score.length; i++) {
if(max < score[i]) {
max = score[i];
} else if(min > score[i]) {
min = score[i];
}
} //이렇게 한번에 처리하다니!!
System.out.println("최댓값 = "+max);
System.out.println("최솟값 = "+min);
}
}
최댓값 = 100
최솟값 = 33
Math.random()
활용 -> 변수n
은 ✨인덱스✨
변수tmp
활용
import java.util.Arrays;
public class Ex5_4 {
public static void main(String[] args) {
int[] nArr = {99, 20, 1, 9, 33, 100, 4, 6, 63, 10};
//인덱스 0~9, 총 10개
System.out.println(Arrays.toString(nArr));
for(int i=0; i<100; i++) { //100번 반복
int n = (int)(Math.random()*10);
//0이상10미만 인덱스 중 하나 선택. n을 인덱스로 잡자
int tmp = nArr[0];
nArr[0] = nArr[n];
nArr[n] = tmp;
//배열[0]과 배열[n]의 값을 바꾸는데, 거기게 tmp 사용!!
}
System.out.println(Arrays.toString(nArr));
}
}
[99, 20, 1, 9, 33, 100, 4, 6, 63, 10]
[4, 1, 9, 63, 99, 10, 6, 20, 33, 100]
[0]
: [0]
와 [랜덤]
이 계속 바뀐다.[99, 20, 1, 9, 33, 100, 4, 6, 63, 10]
[6, 20, 1, 9, 33, 100, 4, 99, 63, 10]
[4, 20, 1, 9, 33, 100, 6, 99, 63, 10]
[10, 20, 1, 9, 33, 100, 6, 99, 63, 4]
[63, 20, 1, 9, 33, 100, 6, 99, 10, 4]
[6, 20, 1, 9, 33, 100, 63, 99, 10, 4]
[63, 20, 1, 9, 33, 100, 6, 99, 10, 4]
기준이 [i]
: [0]
와 [랜덤]
, [1]
와 [랜덤]
, ... [최대치]
와 [랜덤]
여기서 기준을 [0]
을 했지만, [i]
로 해도 된다!
for(int i=0; i<nArr.length; i++) {
//...
int tmp = nArr[i];
nArr[i] = nArr[n];
nArr[n] = tmp;
}
이게 더 좋은 방법
import java.util.Arrays;
public class Ex5_5 {
public static void main(String[] args) {
int[] lotto = new int[45]; //선언, 저장공간 생성
for(int i=0; i<45; i++) {
lotto[i] = i+1;
}
System.out.println(Arrays.toString(lotto));
//각 요소에 숫자 1~45 초기화
for(int i=0; i<6; i++) {
int n = (int)(Math.random()*45); //0이상45미만
int tmp = lotto[i];
lotto[i] = lotto[n];
lotto[n] = tmp;
}
System.out.println(Arrays.toString(lotto));
//앞의 요소6개만 랜덤하게 섞고 그것만 출력하기
System.out.println("당첨번호는 ?");
for(int i=0; i<6; i++) {
System.out.printf("lotto[%d] = %d%n", i, lotto[i]);
}
}
}
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45]
[24, 45, 17, 20, 44, 34, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 3, 18, 19, 4, 21, 22, 23, 1, 25, 26, 27, 28, 29, 30, 31, 32, 33, 6, 35, 36, 37, 38, 39, 40, 41, 42, 43, 5, 2]
당첨번호는 ?
lotto[0] = 24
lotto[1] = 45
lotto[2] = 17
lotto[3] = 20
lotto[4] = 44
lotto[5] = 34
import java.util.Scanner;
public class Main {
public static int max(int a, int b) {
return (a > b) ? a : b;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("몇 개의 숫자를 입력하시겠습니까? : ");
int N = input.nextInt();
int[] arr = new int[N]; // **배열을 만들고 **
for(int i = 0; i < N; i++)
{
System.out.print("자연수를 입력하십시오. : ");
arr[i] = input.nextInt(); // **각 배열에 들어갈 숫자 입력하기**
}
int result = -1;
for(int i = 0; i < N; i++)
{
result = max(result, arr[i]);
}
System.out.print("가장 큰 수는 무엇입니까? : " + result);
input.close();
}
}
- 0 <= x < 1 인 실수를 랜덤하게 뽑는 함수
- 1~100을 하기 위해선 아래와 같이
- ✨ double 이므로 (int)형 변환 주의
0 <= x < 1 -> 100을 곱하면 0 <= x < 100 -> +1을 하면 1 <= x < 101 -> (int) 하면 정수만 구해지기 때문에 => 1 2 3 ... 99 100 인 숫자가 범위가 된다.
- 1~9를 하기 위해선 아래와 같이
- ✨ double 이므로 (int)형 변환 주의
0 <= x < 1 -> 10을 곱하면 0 <= x < 10 -> (int) 하면 정수만 구해지기 때문에 => 1 2 3 ... 9 인 숫자가 범위가 된다.
public class Main {
public static void main(String[] args) {
// 1~100인 정수 100개를 랜덤하게 뽑고 평균값 구하기
int[] arr = new int[100];
int sum = 0;
for(int i = 0; i < 100; i++)
{
arr[i] = (int) (Math.random() * 100 + 1);
sum += arr[i];
}
System.out.println("1~100인 정수 100개의 평균값은 : " + sum / 100);
}
}
1~100인 정수 100개의 평균값은 : 52
String배열
String[] name = new String[3];
null
이다.String[] name = {"Kim", "Yi", "Park"};
String
은 참조형타입의 변수다!! 주소값을 참조하므로 이런 그림이 맞다!!import java.util.Arrays;
public class RspGame {
public static void main(String[] args) {
// 배열에 가위바위보 넣어 랜덤하게 뽑기
String[] rsp = {"가위", "바위", "보"};
System.out.println(Arrays.toString(rsp));
System.out.println("랜덤하게 뽑기 : ");
for(int i=0; i<10; i++) {
int n = (int)(Math.random()*3); //0~2
System.out.println(rsp[n]);
}
}
}
[가위, 바위, 보]
랜덤하게 뽑기 :
가위
바위
가위
바위
가위
바위
보
가위
가위
바위
"입력1"
, "입력2"
...String[] args = {"입력1", "입력2", ...};
args
args
는 문자열배열이므로
public class Ex5_7 {
public static void main(String[] args) {
//커맨드라인 입력하면 위의 args가 참조변수가 된다.
//String[] args 생성!
System.out.println("매개변수의 개수 : "+args.length);
//args의 길이는 매개변수가 몇 개나 들어와 있는지
for(int i=0; i<args.length; i++) {
System.out.printf("args[%d] = %s%n", i, args[i]);
}
}
}
매개변수의 개수 : 4
args[0] = abc
args[1] = 123
args[2] = Hello World
args[3] = ddd
args[4] =
alt + Enter
bin폴더
에 가기 - 클래스에서 해야 하므로cd 경로
입력dir
하면 디렉토리들을 확인할 수 있다.java 해당클래스파일 입력1 입력2 ..
...\bin>
에서 해야한다!! 패키지 안으로 가면 안됨!!!!