-1

I have a list of words e.g : "Moon","Sun","Jupiter","Mars" they are all stored in an array, lets call it "planets"

String[] planets = new String[]{"Moon","Sun","Jupiter","Mars"}

How do i get the number of words that are stored in the array ?

5
  • Actually planets is an array not a string. Can you rephrase? Commented Oct 13, 2011 at 8:08
  • String[] planets = array of string so the array length is your number of words. Commented Oct 13, 2011 at 8:09
  • It's an array, you can get the length of the array like this: planets.length Commented Oct 13, 2011 at 8:10
  • If you want to ask another question, use another Question. Commented Oct 13, 2011 at 8:14
  • 1
    The OP is not really wrong about the planets: the sun and moon were two of the original seven planets. Commented Oct 13, 2011 at 8:14

3 Answers 3

7

Those planets are not stored in one String. They are stored in a String array, so there's a String for each planet. If you want to get the number of planets in the planets array, just use: planets.length.

If you want to build a new array with the first two elements of the array, you can use:

   String[] fewPlanets = new String[]{planets[0], planets[1]};

You might want to take a look at the Arrays Tutorial.

Take into account that there's a typo in the planets array declaration in the question. It should be:

String[] planets = new String[]{"Moon","Sun","Jupiter","Mars"}

If you really had the planets in one string, you could use String.split() with a separator to build an array with each of the planets, and use length to get the length of the array:

String planets = "Moon,Sun,Jupiter,Mars";
String[] planetsArray = planets.split(",");
int numberOfPlanets = planetsArray.length;
Sign up to request clarification or add additional context in comments.

Comments

1

Just length = planets.length

Comments

0

The answer on the first question is: use planets.length to count the number of String's in the array.

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.