Java 在for语句中更改数组时
我想这段时间应该贴上完整的代码 当我试图将值从扫描程序中获取到名为“score”的数组中时 第二个for语句显示意外的结果Java 在for语句中更改数组时,java,Java,我想这段时间应该贴上完整的代码 当我试图将值从扫描程序中获取到名为“score”的数组中时 第二个for语句显示意外的结果 import java.util.Scanner; public class B1546 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int N = input.nextInt(); int[]
import java.util.Scanner;
public class B1546 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int N = input.nextInt();
int[] score = new int[N];
Max scoreMax = new Max();
double sum = 0;
for (int i=0; i<N; i++) {
score[i] = input.nextInt();
}
for (int i=0; i<N; i++) {
System.out.println(score[i]); // this show the problems
sum = sum + ((double) score[i] / scoreMax.max(score) * 100);
}
System.out.println(sum / N);
}
}
class Max {
int max (int[] score) {
int[] tmpArray;
tmpArray = score;
for( int i=0; i<score.length-1; i++) {
for( int j=i+1; j<score.length; j++) {
if (tmpArray[i]<tmpArray[j]) {
int tmp = tmpArray[i];
tmpArray[i] = tmpArray[j];
tmpArray[j] = tmp;
}
}
}
return tmpArray[0];
}
}
import java.util.Scanner;
公共级B1546{
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(System.in);
int N=input.nextInt();
int[]分数=新的int[N];
Max scoreMax=新的Max();
双和=0;
对于(int i=0;i您的Max.Max方法更改数组-以int tmp=
开头的3行
问题的根源可能是不理解引用类型。tmpArray=score
不单独复制数组score
——您只对同一数组有两个引用。这一概念是Java编程的基础
int max (int[] score) {
int[] tmpArray;
tmpArray = score;
}
score
是对数组对象的引用。在这里,您可以创建对现有数组的新引用。若要修复它,请创建一个新数组对象:
int max(int[] score) {
int[] tmpArray = Arrays.copyOf(score, score.length);
}
int[]
是对象,因此在Java中通过引用传递。在Max\Max(int[])
方法中执行以下操作时:
int[] tmpArray;
tmpArray = score;
tmpArray
和score
都将持有相同的引用,因此当您交换tmpArray
中的值时,score
-数组也将被修改
您必须为tmpArray
创建一个新的整数数组,然后复制值。最简单的方法是以下两种方法之一:
int[] tmpArray = score.clone();
// or:
int[] tmpArray = Arrays.copyOf(score, score.length);
我会建议第二个,第二个
tmpArray
和score
实际上都指向完全相同的数组对象。因此,无论何时调用max
,都会混淆score
。