1

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));
    }

}

2 Answers 2

3

You should run it with :

java isPrime 9 

The command line arguments are not passed within parentheses.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.