gpt4 book ai didi

java - 双维数组(素数(和)计数缺陷)

转载 作者:行者123 更新时间:2023-12-01 12:34:10 28 4
gpt4 key购买 nike

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);
}
}

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

最佳答案

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

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;
}
}

关于java - 双维数组(素数(和)计数缺陷),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25708222/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com