日期:2014-05-20  浏览次数:20772 次

java随机数组报错,求教了
import java.util.Random;

public class RandomArray {

/**
 * 使用循环生成随机生成10个随机数并保存至数组中。再找出数组中最大值和最小值,输出到控制台台
 */
public static void main(String[] args) {
Random rnd=new Random();
int[] ns=new int[10];
for(int i=0;i<10;i++){
ns[i]=rnd.nextInt(100);
}


int min=0,max=0;
for(int j=0;j<9;j++){
if(ns(j)>ns(j+1)){
min=ns(j+1);
ns(j+1)=ns(j);
ns(j)=min;

}
}




}

}


代码没有写完
报错:
Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
The method ns(int) is undefined for the type RandomArray
The method ns(int) is undefined for the type RandomArray
The method ns(int) is undefined for the type RandomArray
The left-hand side of an assignment must be a variable
The left-hand side of an assignment must be a variable


}

------解决方案--------------------

import java.util.Random;

public class RandomArray {
    /**
     * 使用循环生成随机生成10个0--99的随机数并保存至数组中。再找出数组中最大值和最小值,输出到控制台台
     */
    public static void main(String[] args) {
Random rnd = new Random();
int[] ns = new int[10];
for (int i = 0; i < 10; i++) {
    ns[i] = rnd.nextInt(100);
}

int min = ns[0], max = ns[0];
for (int j = 1; j < ns.length; j++) {
    if(ns[j]>max) max = ns[j];
    if(ns[j]<min) min = ns[j];
}
System.out.println(max);
System.out.println(min);
    }
}