双维数组(Prime(sum)计数缺陷)

时间:2014-09-07 08:02:38

标签: java primes

import java.util.Scanner;
public class array1 {
    public static void main(String [] args){
        int table[][] = new int[5][5];
        Scanner scan = new Scanner(System.in);
        for(int i =0; i < 5; i++){
            for(int j =0; j < 5; j++){
                System.out.println("Write a value for row " +i + " column " +j);
                int n = scan.nextInt();
                table[i][j] = n;
            }
        }
        for(int i =0; i < 5; i++){
            for(int j =0; j < 5; j++){
                System.out.print(table[i][j] + "\t");
            }
            System.out.println();
        }

        int sum = 0;
        boolean prime = true;
        for(int i =0; i < 5; i++){
            for(int j =0; j < 5; j++){
                for(int e = 2; e < table[i][j]; e++ ){
                    if(table[i][j] % e == 0){
                        prime = false;
                    }
                }
                if(prime == true){
                    sum += table[i][j];
                }
                else{}
            }
        }
        System.out.println();
        System.out.println("Sum of all prime numbers in this array is " +sum);
    }
}

好吧,正如标题本身所说的那样,程序应该总结用户定义的数组表中的所有素数,但它只是总结第一行。我检查了所有括号,没有任何帮助。任何帮助,将不胜感激!谢谢!

1 个答案:

答案 0 :(得分:1)

您应该为每次迭代重置素数:

for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
        for (int e = 2; e < table[i][j]; e++) {
            if (table[i][j] % e == 0) {
                        prime = false;
            }
        }
        if (prime == true) {
            sum += table[i][j];
        } else {
        }
        prime = true;
    }
}