Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
203 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...