0

Trying to create a Prime Number Tester like the code below but when I input java isPrime(9) in the terminal window, I get

-bash: syntax error near unexpected token `('

I want the code to read either true or false back to me.

Can someone also explain to me the function of the main method as I guess my user input is first captured by the main method and then passed on to any other referenced methods. Or is it a matter of placement of the main method in the code, that is to put the main method at the top (or is this irrelevant in java)?

Here is the code.

public class isPrime {

public static boolean isPrime(int N){
    for (int i=3; i == N/2; i++){
        if (N%i==0)
            return true;
    }
    return false;
}

public static void main (String [] args){
    int N = Integer.parseInt(args[0]);
    System.out.println(isPrime(N));
    }

}
Darshan Chaudhary
  • 2,093
  • 3
  • 23
  • 42
Melvin
  • 53
  • 4

2 Answers2

2

You should run it with :

java isPrime 9 

The command line arguments are not passed within parentheses.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

Why does java isPrime(9) cause an error? Well, the bash shell treats () specially. To know more, read the answer to this question - How to use double or single brackets, parentheses, curly braces.

You could quote the brackets to force bash to drop its special treatment of (). Something like java 'isPrime(9)'. But this prints another error: Error: Could not find or load main class isPrime(9).

What just happened? The java command expects to be invoked as java [options] MainClass [arg1 arg2 arg3...]. The first word after java that does not begin with a - is the class to execute. Rest of the words in the command line are made available as args[] in the main(String []args) function.

So, if you want to execute the code in isPrime class with an input of 9, the correct syntax would be java isPrime 9.

Community
  • 1
  • 1
Gowtham
  • 1,465
  • 1
  • 15
  • 26