I'm trying to get better at using OOP with Java. My goal in this exercise is to take user input and check if it is prime using an boolean method. I may have approached this wrong but any advice on what I've created would be most beneficial because I feel like I'm on the right track.
In this program I have two main problems
First, I would like to simply get the isPrime method to be error free. With how I generally approach problems, I have a hard time setting up boolean methods.
The error comes in the last statement because prime variable has not been initialized. But I would like to get the verification whether the variable prime is true or false from the main if-else block though! Is there a way to get that value out of if-else block's scope?
public boolean isPrime(int number){
boolean prime;
if(number == 2){
System.out.println( number + " is prime");
prime = true;
} else{
for(int i = 2; i < number; i++){
if( number % i == 0){
System.out.println(number + " is composite");
prime = false;
break;
} else
System.out.println( number + " is prime");
prime = true;
}
}
return prime;
}
My second huge problem how do I call the isPrime method to print my desired results using user input?
I've been working on this for hours and I can fix one thing and then another error pops up somewhere.
Here's the entire program. The main method is bare because I erased my previous attempts to use the isPrime method. Here it is:
import java.util.*;
public class PrimeChecker{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out
.println("Enter a number to see if it is Prime or Composite: ");
int check = sc.nextInt();
sc.close();
}
public boolean isPrime(int number){
boolean prime;
if(number == 2){
System.out.println( number + " is prime");
prime = true;
} else{
for(int i = 2; i < number; i++){
if( number % i == 0){
System.out.println(number + " is composite");
prime = false;
break;
} else
System.out.println( number + " is prime");
prime = true;
}
}
return prime;
}
}
When you print
number + " is prime"
in theelse
block, you don't yet know that the number is prime. You only know that you haven't yet proven that it's composite. Also, you're probably unable to callisPrime
because you've made it an instance method. It should bestatic
:Then inside your
main()
: