我在完成这个程序时遇到了麻烦。我理解该程序应该做什么,但我在完成它时遇到了麻烦。我的代码发布在下面。
对于这个程序,我需要确定一个数字是否是素数。从这个角度来看,我需要让用户输入一个范围(例如1-10)并显示哪些数字是素数而哪些不是。
这就是我到目前为止......
import java.util.Scanner;
public class PrimeNumbers
{
public static void main(String[]args)
{
//Create Scanner Object
Scanner input = new Scanner(System.in);
//Initialize variable
double num1, range;
//Prompt the user to enter in a number
do
{
System.out.println("Please enter in a number:");
num1 = input.nextDouble();
//Decision making
if(num1 % 2 == 0 || num1 % 3 == 0 || num1 % 4 == 0 || num1 % 5 == 0 || num1 % 6 == 0 || num1 % 7 ==0 || num1 % 8 ==0 || num1 % 9 == 0)
{
//Display message
System.out.println(num1 + " is not a prime number.");
System.out.println("Please enter a range: ");
range = input.nextInt();
if ()
}
else
//Display output
System.out.println(num1 + " is prime.");
}
while(num1 == -1);
{
System.out.println("This program has now ended.");
}
}
}
答案 0 :(得分:1)
http://beginnersbook.com/2014/01/java-program-to-display-prime-numbers/
import java.util.Scanner;
class PrimeNumbers2
{
public static void main (String[] args)
{
Scanner scanner = new Scanner(System.in);
int i =0;
int num =0;
//Empty String
String primeNumbers = "";
System.out.println("Enter the value of n:");
int n = scanner.nextInt();
for (i = 1; i <= n; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to n are :");
System.out.println(primeNumbers);
}
}
答案 1 :(得分:0)
这里是显示特定范围内的素数的代码,
import java.util.Scanner;
public class JavaPrograms
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Please enter the first number : ");
int start = sc.nextInt();
System.out.print("Please enter the second number : ");
int end = sc.nextInt();
System.out.println("List of prime number in java between " + start + " and " + end + " : ");
for(int a = start; a <= end; a++)
{
if(checkPrime(a))
{
System.out.println(a);
}
}
sc.close();
}
public static boolean checkPrime(int number)
{
if(number <= 1)
{
return false;
}
for(int a = 2; a <= Math.sqrt(number); a++)
{
if(number % a == 0)
{
return false;
}
}
return true;
}
}
有关素数java程序的更多信息,请参阅this资源。