0

write a program in java using object oriented principle to check whether a number is prime or not. If it is prime then print 1 if it is false then 0 if the given value is less then or equal to 1 then print -1. Take the values from the user?

when i give single digit values it works but when i give 2 digits value it doesn't work

import java.util.Scanner;

class Prime1 {
int n;
Prime1 (int n)
{
    this.n=n;
}
boolean isPrime()
{
    if(n==2)
    {
        System.out.println("1");
        return true;
       
    }
    else if (n%2==0)
    {
        System.out.println("0");
        return false;
    }
    for (int i = 3;i<=Math.sqrt(n);i+=2)
    {
        if(n%i==0)
        System.out.println("0");
        return false;
    }
    System.out.println("1");
    return true;

}
}


class CheckPrime
{
public static void main(String[] args) 
{
    System.out.print("Enter a number you want to check :: ");
    Scanner scan = new Scanner(System.in);
    int num1 = scan.nextInt();
    scan.close();
    Prime1 obj = new Prime1(num1);
    if(num1<=1)
    {
        System.out.print("-1");
    }        
    else
    {
        obj.isPrime();

    }
}
}
OneCricketeer
  • 151,199
  • 17
  • 111
  • 216
Lo9EWo1F_
  • 3
  • 1
  • seems like a duplicate of https://stackoverflow.com/questions/15743192/check-if-number-is-prime-number. Note that `c#` shares most syntax with `java` so you may put some effort to it and adjust the existing answer to your solution – ymz Apr 03 '22 at 13:15
  • You should move the print statements to your main method, by the way – OneCricketeer Apr 03 '22 at 13:47

1 Answers1

2

change the for loop to

  for (int i = 3;i<=Math.sqrt(n);i+=2)
{
    if(n%i==0)
    {
      System.out.println("0");
      return false;
     }
}

You forgot to put curly bracket after if which results in for loop running only once!