java:Array,如何使用find Distance(距离,名称)功能和显示距离?

时间:2017-11-14 10:21:12

标签: arrays multidimensional-array methods

java:Array,如何使用find Distance(距离,名称)功能和显示距离?
java:Array,如何使用find Distance(距离,名称)功能和显示距离? java:Array,如何使用find Distance(distance,name)函数和显示距离?

package practice;

public class displayDistance 
{   
   /*I'm playing around with Arrays in Java and had this doubt.
     How do I call the  find Distance (distance,name) and display distance .

     5 Requirement are :
     1) Define 2-D Array for distance and populate it. 
     2) ask user for source and destination ( preferably lets use Exception Handling along with JOptionPane prompt .
        e.g. 1st prompt-> From city :  , 2nd prompt->  To city :    
     3)define a city Array 
     4)call function findDistance (distance,name) to find distance and  return it . 
     5)display distance.*/

    public class practice {
        public void main(String[] args) 
        {

          //1. Define 2-D Array for distance and populate it .      
          int [][] distances = { {0,50,100,20},{50,0,70,110},
                               {100,70,0,200},{20,110,200,0} };

          //3. define a city Array          
          String [] names = {"manassas","fairfax","baltimore","centerville"};       

          // calling (invoking)the function         
           findDistance (distances,names);


          // JOptionPane.showMessageDialog(null, "The distance value is: " + findDistance(distances), "DISTANCE VALUE",
          // JOptionPane.INFORMATION_MESSAGE);     

        }   

     private String findDistance(int[][] distances, String[] names) {                       
         return null;
     }
  }
}

1 个答案:

答案 0 :(得分:-1)

import java.util.*;
import java.lang.*;
import java.io.*;

class Demo6 {
    public static void main(String[] args) {


        int[][] distances = {{0, 50, 100, 20}, {50, 0, 70, 110},
                {100, 70, 0, 200}, {20, 110, 200, 0}};


        String[] names = {"manassas", "fairfax", "baltimore", "centerville"};

        /* Take two more inputs which are FROM city TO city */
        /* **I have taken two default city names below** */
        /* And findDistance method should have four arguements */

        findDistance(distances, names, "baltimore", "centerville");


    }


    private static void findDistance(int[][] distances, String[] names, String a, String b) {

        int x = 0, y = 0;

        /*below i am finding the index of the cities 'a' and 'b'*/
        /*below logic works only if both the cities exist  in the array*/

        for (int i = 0; i < names.length; i++) {
            if (names[i].equals(a))
                x = i;
            if (names[i].equals(b))
                y = i;
        }
    /*after calculating the index just print their cost from the matrix distance*/
    /*its as simple as that*/
        System.out.println(distances[x][y]);

    }
}

希望它有所帮助。我在评论中解释了代码。