Hi, I had to make a java coding that will determine if a number is a prime number or not. Here's the coding I did:

    import.java.util.Scanner;
     public class PrimeNumber
    {
    public static void main(String args[]) 
     {
    int n;
    Scanner Prime = new Scanner(System.in);
    System.out.println(" Please enter a number: ");
    n = Prime.nextInt();
    System.out.println(isPrime(n));
    }
    static boolean isPrime(int n) {
    if (n%2==0) return false;
    for(int i=3;i*i<=n;i+=2) {
    if(n%i==0)
    return false;
    }
    return true;
    }
    } 

And I got just 1 more error to correct here:

PrimeNumber.java:1: error: <identifier> expected
    import.java.util.Scanner;
          ^
1 error

Can anyone please shed some light on correcting this 1 error in my java coding here? Thanks in advance!

Dani AI

Generated

correctly spotted the compile error (an extra . in the import). 's switch from printing the raw boolean to an if/else already gives the human‑readable messages the thread asked for. Two important gaps remain, though: the posted prime test treats 2 (and values ≤ 1) incorrectly, and input/resource handling and naming can be tightened.

Key corrections to the trial‑division approach (conceptual):

  • Handle edge cases first: treat any n ≤ 1 as not prime, and n == 2 as prime.
  • Reject even numbers > 2 early.
  • Test only odd divisors up to sqrt(n).
  • Close the Scanner and prefer clear variable names (e.g. scanner not Prime).

An alternative that avoids writing the trial loop and works for very large integers is Java’s BigInteger.isProbablePrime. The example below prints exactly the messages requested and has a comment on every line.

import java.util.Scanner;               // read console input
import java.math.BigInteger;            // arbitrary-size integers and primality helper

public class PrimeNumber {              // program wrapper
    public static void main(String[] args) { // program entry point
        Scanner sc = new Scanner(System.in); // create scanner for stdin
        System.out.print("Please enter a number: "); // prompt for input
        String token = sc.next().trim();   // read one token (safe for big numbers)
        sc.close();                        // close scanner to free resources
        BigInteger n;                      // variable to hold parsed integer
        try {
            n = new BigInteger(token);     // parse input string to BigInteger
        } catch (NumberFormatException e) {
            System.out.println("Invalid integer input."); // handle bad input
            return;                        // exit if parsing failed
        }
        // isProbablePrime(20) — very low false-positive chance for casual use
        if (n.isProbablePrime(20))
            System.out.println("This is a prime number");
        else
            System.out.println("This is NOT a prime number");
    }
}

Notes: isProbablePrime(certainty) is probabilistic; increase certainty for higher assurance or use deterministic routines for cryptographic needs. For simple coursework and 32‑bit ints, a corrected trial‑division check (handle 0/1/2, then test odds to sqrt(n)) is perfectly adequate and fast.

Recommended Answers

All 5 Replies

Look up the correct syntax for the import statement - you have an extra . that shoudn't be there.

Alright. I did the correction. And now the coding has no more errrors. And here's the coding:

    import java.util.Scanner;
    public class PrimeNumber
    {
    public static void main(String args[])
    {
    int n;
    Scanner Prime = new Scanner(System.in);
    System.out.println(" Please enter a number: ");
    n = Prime.nextInt();
    System.out.println(isPrime(n));
    }
    static boolean isPrime(int n) {
    if (n%2==0)return false;

    for(int i=3;i*i<=n;i+=2) {
    if(n%i==0)
     return false;
    }
    return true;
     }
    } 

And here's the output when I gave an input number of 3:

Please enter a number: 
3
true

BUT THE PROBLEM HERE IS that I want the output to return **" This is a prime number " **if the input number given is a prime number

AND

I want the output to return " This is NOT a prime number " if the input number given is NOT a prime number.

So, can anyone please help me to improvise this coding to produce the output I want?
Thanks in advance!

Here, this should do it. I just replaced the

System.out.println(isPrime(n));

part, which would print true or false, with an if

if (isPrime(n))
    System.out.println("The number is prime.\n");
else 
    System.out.println("The number is not prime.\n");

Here's the code:

import java.util.Scanner;
public class PrimeNumber{
    public static void main(String args[]){
        int n;
        Scanner Prime = new Scanner(System.in);
        System.out.println(" Please enter a number: ");
        n = Prime.nextInt();
        if (isPrime(n))
            System.out.println("The number is prime.\n");
        else 
            System.out.println("The number is not prime.\n");
    }

    static boolean isPrime(int n) {
        if (n%2==0)return false;
        for(int i=3;i*i<=n;i+=2) {
            if(n%i==0)
                return false;
        }
        return true;
    }
} 

This is a trivial task. You should probably read your coursebook/tutorials, I bet you'll find the answers there.

Thanks, Lucaci Andrew. Can you also leave a comment for each lines of the coding in explainations of what each line's purpose is for? Like this one I did here(but it's not complete since I do not know all the main functions and purposes of each lines in this coding..)

    import java.util.Scanner;
    public class PrimeNumber{ //The class name here is PrimeNumber
    public static void main(String args[]){
    int n;
    Scanner Prime = new Scanner(System.in);
    System.out.println(" Please enter a number: ");
    n = Prime.nextInt();
    if (isPrime(n))
    System.out.println("The number is prime.\n");
    else
    System.out.println("The number is not prime.\n");
    }
    static boolean isPrime(int n) {
    if (n%2==0)return false;
    for(int i=3;i*i<=n;i+=2) { //This line defines an integer 'i' as the integer other than 1 and the given number. That means, i>2 and i<num.
    if(n%i==0)
    return false;
    }
    return true;
    }

Hope you can lend some advisable solutions on this, thanks in advance!

Well it's your function, so you know what you did in there. I just added that if statement. Also, as I told you before, this things are quite elementary, and you'll find them in any programming book. I suggest you to review your course/lecture and re-read it, or read your course book.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.