0

This is the code I wrote about a prime number question using java but when I run the code it says something about java string formatter. Help me find out whats wrong please.

import java.util.Scanner;

public class Hello {

public static void main(String args[]) {

    int checker=2;

    boolean [] prime= new boolean [1000];

    for(int i = 0; i < prime.length; i++)
        {
            prime[i] = true;
        }

    do
    {

    for(int i=2;i<prime.length;i++)
    {
        if((i % checker) == 0)
        {
            prime[i]=false;
        }
    }
    checker++;
    } while(checker!=999);

    for(int i = 0; i < prime.length; i++)
        {
            System.out.printf("%5c",prime[i]);
        }
 }
}
1
  • Please describe what goes wrong and what you have already tried. Commented May 7, 2015 at 10:45

3 Answers 3

3

Your exception is not because of the array but because of the array type:

System.out.printf("%5c",prime[i]);

your prime array is a boolean array, whereas the string format %c expects a Unicode character. For boolean you'll need %b as such:

System.out.printf("%5b",prime[i]);
Sign up to request clarification or add additional context in comments.

3 Comments

Note: It'll print false if prime[i] is null, should be aware of this.
@MarounMaroun how boolean primitive can be null?
@SashaSalauyou Indeed. As I said, I didn't note.
0

Change your output to:

System.out.println(i + (prime[i] ? " is prime" : " is not prime"));

It uses ternary operator as shortcut of if (prime[i]) ... else ... to generate the output like

1 is not prime
2 is prime
3 is prime
4 is not prime
... 

1 Comment

While this code may answer the question, a few words of explanation will help current and future readers understand this answer even better.
0

For printing boolean you just print -

System.out.printf(prime[i]);

Or you may use %b as format specifier -

System.out.printf("%5b",prime[i]);

Comments

Your Answer

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