作者laechan (小太保)
看板mud_sanc
标题[分享] JAVA part2
时间Tue Jan 15 13:30:02 2013
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)
1F:推 ckstorm :shallow copy vs. deep copy的概念, 01/22 20:10
2F:→ ckstorm :只是多贴一张不同名字的贴纸到同个object上 01/22 20:10
我觉得它有个地方很烦人。
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)
3F:推 ckstorm :Maybe you can ref BeanUtil.copyProperties 01/26 20:14
4F:→ laechan :what's that?? 01/26 22:29
5F:推 ckstorm :一时找不到什麽好的例子的网页, 先贴个Java API 01/27 23:57
7F:推 ckstorm :供您参考 by对板上感兴趣,潜水很久曾当过wiz的路人甲 01/28 00:00