我正在尝试编写一个简单的程序,该程序给出数组大小为 40 的最大值、最小值、偶数个数、奇数个数和素数个数。
我写了以下代码:
package TESTING;
import java.util.*;
public class testClass{
public static void main (String args[]){
int numbers[]= {1,5,-9,12,-3,89,18,23,4,-6,14,-5,87,17,47,-73,39,49,56,71,
3,0,-2,23,-8,45,63,71,5,29,-4,15,78,37,99,-66,44,94,65,73};
//Find minimum (lowest) value in array using loop
System.out.println("Minimum Value = " + getMinValue(numbers));
//Find maximum (largest) value in array using loop
System.out.println("Maximum Value = " + getMaxValue(numbers));
System.out.println("Even Numbers = " + even(numbers));
System.out.println("Odd Numbers = " + odd(numbers));
for(int number = 1; number<=numbers.length; number++){
//print prime numbers only
if(isPrime(numbers)){
System.out.println("+ numbers");
}
}
//Find maximum (largest) value in array using loop
public static int getMaxValue(int[] numbers){
int maxValue = numbers[0];
for(int i=1;i<numbers.length;i++){
if(numbers[i] > maxValue){
maxValue = numbers[i];
}
}
return maxValue;
}
//Find minimum (lowest) value in array using loop
public static int getMinValue(int[] numbers){
int minValue = numbers[0];
for(int i=1;i<numbers.length;i++){
if(numbers[i] < minValue){
minValue = numbers[i];
}
}
return minValue;
}
//Find even numbers in array
public static int even(int[] numbers)
{
int countLength = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
countLength++;
}
}
return countLength;
}
public static int odd(int[] numbers)
{
int countOdd =0;
for (int i=0; i<numbers.length; i++) {
if (numbers[i] %2 != 0){
countOdd++;
}
}
return countOdd;
}
public static boolean isPrime(int numbers[]){
for(int i=2; i<numbers.length; i++){
if(numbers.length%i == 0){
return false; //number is divisible so its not prime
}
}
return true; //number is prime now
}
}
没看懂问题出在哪里?它没有在输出中显示素数。我得到以下输出:
输出
Minimum Value = -73
Maximum Value = 99
Even Numbers = 14
Odd Numbers = 26