[分享] Java part2
package helloworld2;
import java.util.Scanner; // import Scanner 物件來做 input_to
import java.util.Arrays; // import Arrays 物件來做陣列處理
public class HelloWorld2
{
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in); // 類似複製一個 Scanner 的物件
int c;
int[] scores = {88,77,66,55,44};
int[][] XY = { {1,2,3},{4,5} };
int[] d = new int[10];
int[] score2 = Arrays.copyOf(score1,score1.length);
System.out.print("請輸入一個數字: ");
c = scanner.nextInt();
System.out.printf("你輸入的數字是 %d.\n",c);
for(int s : scores)
System.out.printf("學生分數: %d\n",s);
for(int[] row : XY)
{
for(int y in row)
System.out.printf("%2d",y);
System.out.println();
}
for(int c : d)
System.out.printf("%2d",c);
for(int s : score2)
System.out.printf("%2d",s);
}
}
相當於底下
void main()
{
string cs;
write("請輸入一個數字: ");
input_to("main2",0,cs);
return ;
}
void main2(string cs)
{
int c=atoi(cs),s,x,y;
mixed scores=({88,77,66,55,44});
mixed XY=({ ({1,2,3}),({4,5}),}),row=({});
mixed d;
mixed score2=scores;
d=allocate(10); // 初始配置大小
printf("你輸入的數字是 %d.\n",c);
foreach(s in scores)
printf("學生分數: %d\n",s);
foreach(row in XY) // 嗯..不確定, 但似乎可以XD
{
foreach(y in row)
printf("%2d",y);
write("\n");
}
foreach(c in d)
printf("%2d",c); // 觀看初始化值的配置是否為 0 0 0 0 0 0 0 0 0 0
foreach(s in score2)
printf("%2d",s); // 確認陣列有複製成功.
}
Scanner scanner = new Scanner(System.in);
這個就相當於,Scanner 類似一個防具檔,而 scanner
類似 clone(該防具檔) 出來的物件。
概念是類似的。
另外在 Java 裡頭,是不能先宣告一個 score1 陣列,
再令 score2 = score1 的,它的結果會類似 mapping
變數那樣,你在 score2 做的修改會使得 score1 的內
容也跟著變更。因此在 Java 裡要做陣列複製,簡單的
方法之一就是 import java.util.Arrays 再使用
int[] score2 = Arrays.copyOf(score1,score1.length);
注意 O 要大寫.
Laechan
--
※ 發信站: 批踢踢實業坊(ptt.cc)
※ 編輯: laechan 來自: 114.38.29.240 (01/15 14:19)
推
01/22 20:10, , 1F
01/22 20:10, 1F
→
01/22 20:10, , 2F
01/22 20:10, 2F
我覺得它有個地方很煩人。
int[][] c1 = { {1,2,3},{4,5} };
宣告 c1 為一個二維陣列,則底下情況
int[][] c2 = Arrays.copyOf(c1,c1.length);
其結果是令 c2[0][0] = 9 時, c1 的[0][0] 也會變成 9。
個人的解讀是,c2 那行,會產生一個新的二維陣列空間,
即 c1 有一個,c2 也有一個,但是其元素值部份,c2 的
各個元素值會指向 c1 的各個元素值。
解決方法之一是做 deep copy:
int[][] c2 = new int[2][3];
for(i=0;i<c1.length;i++)
c2[i] = Arrays.copyOf(c1[i],c1[i].length);
(當然還有其它解法)
※ 編輯: laechan 來自: 1.165.164.2 (01/22 20:15)
推
01/26 20:14, , 3F
01/26 20:14, 3F
→
01/26 22:29, , 4F
01/26 22:29, 4F
推
01/27 23:57, , 5F
01/27 23:57, 5F
→
01/27 23:57, , 6F
01/27 23:57, 6F
推
01/28 00:00, , 7F
01/28 00:00, 7F
mud_sanc 近期熱門文章
PTT遊戲區 即時熱門文章
29
45
13
23
405
837