Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java: Int to String to Char

  1. Oct 30, 2006 #1
    How come when I exectue this program, I get the follwing error. Just to let you know, what i am trying to do is, check if ever digit in a number is a prime number.

    Code (Text):
    import java.lang.Math;
     
    public class PrimeNumbers
    {
        public static void main (String[] args)
        {
            int[] test = {546513, 77777, 24756, 2226};
           
            for(int i = 0; i<test.length; i++)
            {
                System.out.println ("Integer " + test[i] + " is a prime " + arePrime(test[i]));
            }
        }
       
        public static boolean arePrime(int value)
        {
            char prime2 = '2';
            char prime3 = '3';
            char prime5 = '5';
            char prime7 = '7';
           
            boolean arePrimeDigits = false;
           
            String valueStr = String.valueOf(value);
           
            for (int i = 0; i<valueStr.length(); i++)
            {
                if((valueStr.charAt(i)).equals(prime2) || (valueStr.charAt(i)).equals(prime3) ||
                (valueStr.charAt(i)).equals(prime5) || (valueStr.charAt(i)).equals(prime7))
                {
                    arePrimeDigits = true;
                }
                else
                {
                    arePrimeDigits = false;
                    i = valueStr.length();
                }
            }
           
            return arePrimeDigits;
        }
    }

     
     
    Last edited by a moderator: Oct 30, 2006
  2. jcsd
  3. Oct 30, 2006 #2

    0rthodontist

    User Avatar
    Science Advisor

    A char is not an object, so you can't ask if it .equals() anything. Just use ==.

    Also 2 notes on your code style: First, there's no need to define constants prime2, prime3, etc. It's good to define constants for anything that might change in the future, but the primes are not going to change. Second, your loop is a bit clumsy. Don't set a variable to true every time--just return false if any digit is not prime. You might write it like

    Code (Text):

            for (int i = 0; i<valueStr.length(); i++)
            {
                if any digit is not prime
                    return false;
        }
    return true;
     
     
    Last edited: Oct 30, 2006
  4. Oct 30, 2006 #3
    Oh, I see, thanks very much. I removed the equals and replaced it with == and it worked.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?