-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 ?

Kiesa
  • 407
  • 1
  • 19
  • 42

3 Answers3

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;
Xavi López
  • 27,550
  • 11
  • 97
  • 161
1

Just length = planets.length

Jagat
  • 1,392
  • 2
  • 15
  • 25
0

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

JNDPNT
  • 7,445
  • 2
  • 34
  • 40