62,614
社区成员
发帖
与我相关
我的任务
分享
class Sort
{
public static void printArray(int [] temp){ //对数组进行打印的方法
for(int x : temp){
System.out.print(x + "\t");
}
System.out.println();
}
public static void turn(int [] temp){ //数组转置的方法
int [] t = new int [(temp.length)];
int foot = temp.length -1;
for(int x = 0 ; x < temp.length ; x++){
t[foot --] = temp[x];
}
temp = t;
}
}
public class ArrayDemo
{
public static void main(String args[]){
int data [] = new int [] {8,9,0,2,3,5,10,7,6,1};
Sort.turn(data);
Sort.printArray(data);//输出:8,9,0,2,3,5,10,7,6,1
}
}
class Sort
{
public static void printArray(int [] temp){ //对数组进行打印的方法
for(int x : temp){
System.out.print(x + "\t");
}
System.out.println();
}
public static int[] turn(int [] temp){ //数组转置的方法
int [] t = new int [(temp.length)];
int foot = temp.length -1;
for(int x = 0 ; x < temp.length ; x++){
t[foot --] = temp[x];
}
return t;
}
}
public class ArrayDemo
{
public static void main(String args[]){
int data[]= new int [] {8,9,0,2,3,5,10,7,6,1};
data=Sort.turn(data);
Sort.printArray(data);
}
}
class Sort
{
public static void printArray(int [] temp){ //对数组进行打印的方法
for(int x : temp){
System.out.print(x + "\t");
}
System.out.println();
}
public static int[] turn(int [] temp){ //数组转置的方法
int [] t = new int [(temp.length)];
int foot = temp.length -1;
for(int x = 0 ; x < temp.length ; x++){
t[foot --] = temp[x];
}
return t;
}
}
public class ArrayDemo
{
public static void main(String args[]){
int data[]= new int [] {8,9,0,2,3,5,10,7,6,1};
data=Sort.turn(data);
Sort.printArray(data);
}
}
[/quote]
非常感谢前辈的回复,提供返回值的方法确实能够解决这个问题,而且简单明了。
不过,关于“变量作用域”,我其实还是不明白为什么会错。我之所以在这个问题上这么纠结,是因为数组是引用数据类型,在我的代码中,通过引用传递,temp [ ]→data[ ] ,之后在turn( )中通过一系列操作,将data[ ]中的元素前后顺序颠倒赋值给新的数组t[ ] ,然后把赋值之后的数组t[ ]重新赋值还给data[ ],这个过程为什么会涉及到变量作用域的问题?
我在我的代码中重新增加了测试变量数值,请看下面的代码:
class Sort
{
public static void printArray(int [] temp){ //对数组进行打印的方法
for(int x : temp){
System.out.print(x + "\t");
}
System.out.println();
}
public static void turn(int [] temp){ //数组转置的方法
int [] t = new int [(temp.length)];
int foot = temp.length -1;
for(int x = 0 ; x < temp.length ; x++){
t[foot --] = temp[x];
}
printArray(t); //输出:1 6 7 10 5 3 2 0 9 8
temp = t;
printArray(temp); //输出:1 6 7 10 5 3 2 0 9 8
}
}
public class ArrayDemo
{
public static void main(String args[]){
int data [] = new int [] {8,9,0,2,3,5,10,7,6,1};
Sort.turn(data);
Sort.printArray(data); //输出:8 9 0 2 3 5 10 7 6 1
}
}
当然,我也知道,解决这个数组转置问题可以通过修改代码有多种实现方式和思路,我只是想弄明白程序输出意想不到的结果的原因究竟是什么?是不是我对某个哪个知识点的理解本身就有问题,希望前辈不吝赐教。 public static void turn(int [] temp){ //数组转置的方法
int [] t = new int [temp.length];
int tempx;
for(int x = 0 ; x < temp.length/2 ; x++){
tempx=temp[x];
temp[x]=temp[temp.length-x-1];
temp[temp.length-x-1]=tempx;
}
temp = t;
}