public class Chpt5_Project{
public static void main(String[] args) {
// Declare Variables
int randomNumbers = 0;
int sum = 0;
//Loop for number generation and print out numbers
System.out.print("The five random numbers are: ");
for (int i = 0; i <= 4; i++)
{
randomNumbers = (int)(Math.random()*20);
sum += randomNumbers;
if (i == 4) {
System.out.println("and " + randomNumbers + ".");
}
else {
System.out.print(randomNumbers + ", ");
}
}
//Display Sum
System.out.println("\nThe sum of these five numbers is " + sum + ".\n");
// Test if number is prime
boolean isPrime = true;
for (int divisor = 2; divisor <= sum / 2; divisor++)
if (sum % divisor == 0) { // If true, number is not prime
isPrime = false; // Set isPrime to false
System.out.println("The sum is not a prime number.");}
else {
System.out.println("The sum is a prime number.");
break;
}
}
}
示例输出
五个随机数是:5,0,10,6和13。
这五个数字的总和是34。
总和不是素数。总和是素数。
答案 0 :(得分:0)
您需要添加for-loop
的括号,然后在break
中添加if-statement
语句。
for (int divisor = 2; divisor <= sum / 2; divisor++){
if (sum % divisor == 0) { // If true, number is not prime
isPrime = false; // Set isPrime to false
System.out.println("The sum is not a prime number.");
break;
}
else {
System.out.println("The sum is a prime number.");
break;
}
}