If you do not already have the Java development kit (JDK) installed, download an
ID: 3793851 • Letter: I
Question
If you do not already have the Java development kit (JDK) installed, download and install it (Oracle Corporation, 2013b). You may use an integrated development environment (IDE) of your choice if you wish.
Solve the following programming problems in Java. Submit your source files including several test cases to show your solutions work as expected.
Write a program that prompts the user for a number and outputs whether the number is prime.
Examples:
Enter a number: 13
Thinking (this may take a while)…
The number 13 is prime.
Enter a number: 64000
Thinking (this may take a while)…
The number 64000 is composite (not prime).
Enter a number: 7919
Thinking (this may take a while)…
The number 7919 is prime.
Explanation / Answer
package org.studenrts;
import java.util.Scanner;
public class PrimeOrComposite {
public static void main(String[] args) {
//Declaring variables
int number;
boolean bool;
char ch;
// Scanner object is used to get the inputs entered by the user
Scanner sc = new Scanner(System.in);
//This loop continues to execute until the user enters other than 'Y' or 'y'
while (true) {
//Getting the Number entered by the user
System.out.print("Enter a number: ");
number = sc.nextInt();
//Calling the method by passing the user entered number as argument
bool = isPrime(number);
System.out.println("Thinking (this may take a while)…");
//Displaying the result based on the boolean value returned by the method
if (bool) {
System.out.println("The number " + number + " is Prime ");
} else {
System.out.println("The Number " + number + " is Composite ");
}
// Getting the character from the user 'Y' or 'y' or 'N' or 'n'
System.out.print("Do you want to continue(Y/N) ::");
ch = sc.next(".").charAt(0);
if (ch == 'Y' || ch == 'y')
continue;
else {
System.out.println(":: Program Exit ::");
break;
}
}
}
/* This method will check whether the number is prime or not
* Params :integer type number
* Return :boolean value.
*/
private static boolean isPrime(int number) {
if (number < 2)
return false;
// If the user entered number is '2' return true
else if (number == 2)
return true;
for (int i = 2; i * i <= number; i++) {
if (number % i == 0)
return false;
}
return true;
}
}
_________________
output:
Enter a number: 13
Thinking (this may take a while)…
The number 13 is Prime
Do you want to continue(Y/N) ::Y
Enter a number: 64000
Thinking (this may take a while)…
The Number 64000 is Composite
Do you want to continue(Y/N) ::Y
Enter a number: 7919
Thinking (this may take a while)…
The number 7919 is Prime
Do you want to continue(Y/N) ::N
:: Program Exit ::
___________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.