面向对象程序设计-java语言第三周编程题——查找里程(Mooc)

题目:查找里程

题目内容:

下图为国内主要城市之间的公路里程:
在这里插入图片描述
你的程序要读入这样的一张表,然后,根据输入的两个城市的名称,给出这两个城市之间的里程。
注意:任何两个城市之间的里程都已经给出,不需要计算经第三地中转。
注意:你并不需要去录入上图的数据,数据是在程序输入中给的。

输入格式:
首先,你会读到若干个城市的名字。每个名字都只是一个英文单词,中间不含空格或其他符号。当读到名字为“###”(三个#号)时,表示城市名字输入结束,###并不是一个城市的名字。如果记读到的城市名字的数量为n。
然后,你会读到n * n的一个整数矩阵。第一行的每一个数字,表示上述城市名单中第一个城市依次到另一个城市之间的里程。表中同一个城市之间的里程为0。
最后,你会读到两个城市的名字。

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

输入样例:
Hagzou Hugzou Jigxng ###
0 1108 708
1108 0 994
708 994 0
Hagzou Jigxng

输出样例:
708

代码实现:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

public class Main {
	private ArrayList<String> citys = new ArrayList<String>();
	private HashMap<String, HashMap<String, Integer>> distince = new HashMap<String, HashMap<String, Integer>>();
	private static Scanner in = new Scanner(System.in);
	private String start, end;
	public void input() {
		String city;
		//reading city
		while (true) {
			city = in.next();
			if (city.equals("###") == true)
				break;
			else {
				citys.add(city);
			}
		}
		//reading distince
		for (int i=0; i<citys.size(); i++) {
			HashMap<String, Integer> city_hashmap = new HashMap<String, Integer>();
			for (int j=0; j<citys.size(); j++) {
				int dis = in.nextInt();
				city_hashmap.put(citys.get(j), dis);
			}
			distince.put(citys.get(i), city_hashmap);
		}	
	}
	//search city and city distince
	public void ccdistince() {
		int dis = 0;
		this.start = in.next();
		this.end = in.next();
		dis = distince.get(start).get(end);
		System.out.println(dis);
	}
		
	public static void main(String[] args) {
		// TODO Auto-generated method stub	
		Main dis = new Main();
		dis.input();
		dis.ccdistince();
		in.close();
	}
}

心得体会:
这道题,我们可以通过ArrarList 类集 和 HashMap 类集 ,共同使用这两个对象容器(泛型容器和集合容器) 来解决问题。
学会了通过嵌套HashMap类集来达到存储两个城市之间的路程。并且通过这次作业,让我更加深刻的理解和熟练运用对象容器这一操作。


原文链接:
https://blog.csdn.net/weixin_43347550/article/details/105917317

猜你喜欢

转载自blog.csdn.net/weixin_43347550/article/details/105917317