
int[] intArray = new int[5];
- 디폴트 初期化
// 基本 資料型 配列은 값을 안 넣으면 모든 要素 0으로 初期化 int[] ar = new int[10] // 宣言 客體生成 // 인스턴스 配列(參照變數 配列)은 모든 要素 null로 初期化 String[] ar = new String[10];
- 값을 넣어서 初期化
int[] ar = {1, 2, 4}; String course[] = {"Java", "C++", "HTML5"};
int[] arl = new int[5];
class Box2Main {
public static void main(String[] args) {
Box2[] ar = new Box2[5];
ar[0] = new Box2(101, "Coffee");
ar[1] = new Box2(202, "Computer");
ar[2] = new Box2(303, "Apple");
ar[3] = new Box2(404, "Dress");
ar[4] = new Box2(505, "Fairy-tale book");
for (Box2 e: ar) {
if (e.getBoxNum() == 505) {
System.out.println(e);
}
}
}
}
public class Box2 {
int boxNum;
String contents;
public Box2() {
}
public Box2(int boxNum, String contens) {
this.boxNum = boxNum;
this.contents = contens;
}
public int getBoxNum() {
return boxNum;
}
public String toString() {
return contents;
}
}
結果畫面 →
Fairy-tale book
public class ArrayFor {
public static void main(String[] args) {
String[] sr = new String[7];
sr[0] = new String("Java");
sr[1] = new String("System");
sr[2] = new String("Compiler");
sr[3] = new String("Park");
sr[4] = new String("Tree");
sr[5] = new String("Dinner");
sr[6] = new String("Brunch Cafe");
int cnum = 0;
for (int i = 0; i < sr.length; i++) {
cnum += sr[i].length();
}
cnum = 0;
for (String string : sr) {
cnum += string.length();
}
System.out.println("總 文字의 數 : " + cnum);
}
}
public class Lotto {
public static void main(String[] args) {
int[] lottoArr = new int[6];
for (int i = 0; i < lottoArr.length; i++) {
lottoArr[i] = (int) (Math.random() * 45 + 1);
// 1 ~ 45까지 亂數 生成
// 重複 除去 로직
for (int j = 0; j < i; j++) {
if (lottoArr[i] == lottoArr[j]) {
i--;
break;
}
}
}
for (int num : lottoArr) {
System.out.println(num);
}
}
}