0

I am working on a project where the user enters a planet name and the program uses an array to verify that it is a real planet and a seperate array to hold each planets diameters. The diameter array is set up so its entries are in the same order are the entries in the planet name array. I will put them both below for the sake of reference:

String[] verifyPlanet = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"};
double[] getDiameter = {3031.9, 7520.8, 7917.5, 4214.3, 86881, 72367, 31518, 30599};

I am looking for a way to find what entry number a planet is in the first array, and use it to find the diameter in the second. for example, the user would enter "Mercury", it would be confirmed to be a planet name, then I would somehow have a command that outputs 0, so i could simply enter getDiameter[Arrays.COMMANDEXAMPLE(verifyPlanet)] to output the corresponding diameter. just for the sake of avoiding ambiguity, I am looking for the code that would replace COMMANDEXAMPLE so that command outputs 0. Thanks in advance!

0

2 Answers 2

2

You could use Arrays.asList to create a List from the array and use the indexOf method.

final List<String> planetList = Arrays.asList(verifyPlanet);
int index = planetList.indexOf("Mercury");//0

The more efficient, albeit less convenient, way would be to implement your own indexOf method for a String array.

public static void main(final String[] args) {
    final String[] verifyPlanet = { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune" };
    System.out.println(indexOf(verifyPlanet, "Mercury"));//0
}

private static int indexOf(final String[] arr, final String search) {
    for (int i = 0, len = arr.length; i < len; i++) {
        if (arr[i].equals(search)) {
            return i;
        }
    }
    return -1;
}
Sign up to request clarification or add additional context in comments.

Comments

0

First check if lets say "Earth" is in the array or not:

String planetName = "Earth";
for(String str: verifyPlanet){
     if(str.equals(planetName)){
         for(int i=0;i < verifyPlanet.length;i++){
             if(verifyPlanet[i] == "Earth"){
                 double diameter = (double)Array.get(getDiameter, i);
}}}}

This is the most basic way to do this. Other ways exist to reduce this code to. Can use indexOf() method to get value too. But if your application is not too big, then it is simple and easy to understand.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.