查找里程(Java自学第4天)

输入格式:

首先,你会读到若干个城市的名字。每个名字都只是一个英文单词,中间不含空格或其他符号。当读到名字为“###”(三个#号)时,表示城市名字输入结束,###并不是一个城市的名字。如果记读到的城市名字的数量为n。

然后,你会读到nxn的一个整数矩阵。第一行的每一个数字,表示上述城市名单中第一个城市依次到另一个城市之间的里程。表中同一个城市之间的里程为0。

最后,你会读到两个城市的名字。

 

输出格式:

输出这两个城市之间的距离。

 

输入样例:

Hagzou Hugzou Jigxng    ###

0 1108 708

1108 0 994

708 994 0

Hagzou    Jigxng

 

输出样例:

708

-------------------------------分割线:下面代码--------------------------------------

mport java.util.HashMap;
import java.util.Scanner;

public class 查找里程 {
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String x;
        foundLiCheng LC = new foundLiCheng();
        Scanner in = new Scanner(System.in);
        x = in.next();
        while(!x.equals("###"))
        {
            LC.insert(x);
            x = in.next();
        }
        LC.create();
        String a = in.next();
        String b = in.next();
        
        System.out.println(LC.found(a, b));
    }

}

class foundLiCheng
{
    private HashMap<Integer, String> City = new HashMap<Integer, String>();//创建集合容器,用来存城市名和城市对应数组的下标
    private int id = 0; //下标
    private int[][] d = new int[100][100];//创建二维数组,存城市到城市的距离
    //添加城市名
    public void insert(String city)
    {
        City.put(id, city);
        id++;
    }
    //根据输入的城市数量,创建对应的二维数组存城市到城市的距离
    public void create()
    {
        int[][] LiCheng = new int[City.size()][City.size()];
        Scanner in = new Scanner(System.in);
        for(int i=0;i<City.size();i++)
        {
            for(int j=0;j<City.size();j++)
            {
                LiCheng[i][j] = in.nextInt();
            }
        }
        d = LiCheng;
    }
    /*  */
    public int getSize()
    {
        return id;
    }
    //根据两个城市名找对应距离
    public int found(String a,String b)
    {
        int x=0,y=0;
        int count=0;
        //通过for each 遍历 城市名找到对应的数组下标
        for(int key : City.keySet() )
        {
            if(City.get(key).equals(a))
            {
                x = key;
                count++;
            }
            if(City.get(key).equals(b))
            {
                y = key;
                count++;
            }
        }
        //如果两个都找到 返回对应的距离
        if(count == 2)
        {
            return d[x][y];
        }
        else
        {
            System.out.println("查询的城市距离没记录!");
            return -1;
        }
    }
}

结果:

79373727f9e1f7496f3a47dd3a5716b02c5.jpg

转载于:https://my.oschina.net/u/4069817/blog/3004274

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值