java写了,在一个元素值100以内,含20个元素的一维整形数组元素中,求最大值,平均,素数个数

2025-04-26 01:36:21
推荐回答(1个)
回答1:

import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.Date; public class Solution { int[] rlist; Random r ; Integer max = null; int length; int cursor; public Solution(int length) { this.length = length; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } private int getRnum(){ return r.nextInt(900) + 100; } private void checkIfMax(){ max = cursor == 0 ? 0 : ( rlist[max] >= rlist[cursor] ? max : cursor ); } public void run(){ rlist = new int[length]; max = null; r = new Random((new Date()).hashCode()); for(cursor = 0; cursor < length; cursor++){ rlist[cursor] = getRnum(); checkIfMax(); System.out.print(rlist[cursor]); if(cursor == length - 1){ System.out.print("\n"); }else if((cursor+1)%5 == 0){ System.out.print(",\n"); }else{ System.out.print(", "); } } System.out.println("MAX: " + rlist[max] + ", Location: " + max); } public static void main(String[] args) { Solution s = new Solution(123); s.run(); }}