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!

tdmsoares
  • 533
  • 7
  • 24
gravyGus
  • 11
  • 2

2 Answers2

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;
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
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.

Karan Saxena
  • 49
  • 12