创新实训二十七

在ideal中用java计算距离
由于常常需要使用pycharm。但是又必须运行计算距离的程序,所以考虑在ideal中运行,方法如下:

import java.io.*;
import java.math.BigDecimal;
import java.sql.*;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.concurrent.*;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

public class temp_cxsx {

    public static void main(String []args){
        //数据库连接
        String URL="jdbc:mysql://8.140.178.29:3306/cxsx?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf8";
        String NAME="cxsx";//登录名
        String PASSWORD="cxsx123";//密码
        Connection con = null;
        Statement statement = null;
        ResultSet res = null;
        String path="C:\\Users\\小风淅淅\\IdeaProjects\\PatternClassification\\src\\lab1\\position.txt";
        try {
            ArrayList<String> positions=readF1(path);

            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("成功加载驱动程序");

            con = DriverManager.getConnection(URL,NAME,PASSWORD);
            statement = con.createStatement();
            System.out.println("获取数据库连接成功!");
            String sql="select * from hotel_jinan";
            PreparedStatement pre = con.prepareStatement(sql);
            //得到所有酒店
            ResultSet re = pre.executeQuery();

            String start;
            String end;
            float score=0;
            int comments=0;
            float price=0;
            String type="";
            //计算每个景点到每家酒店的距离
            for (int i =0 ;i<positions.size();i++){
                start = positions.get(i);
                int k=0;
                while(re.next()){
                    System.out.println(start);
                    //计算距离
                    try {
                        end = re.getString(1);
                        System.out.println(end);
                        String startLonLat = getLonLat(start);
                        String endLonLat = getLonLat(end);
                        ExecutorService executor = Executors.newSingleThreadExecutor();
                        FutureTask<Integer> future =
                                new FutureTask<Integer>(new Callable<Integer>() {//使用Callable接口作为构造参数
                                    public Integer call() {
                                        //真正的任务在这里执行,这里的返回值类型为String,可以为任意类型
                                        try {
                                            int dis = getDistance(startLonLat, endLonLat);
                                            return dis;
                                        }
                                        catch (Exception e){
                                            return 9999;
                                        }
                                    }});
                        executor.execute(future);
                        int dis=9999;
                        try {
                            dis = future.get(3000, TimeUnit.MILLISECONDS); //取得结果,同时设置超时执行时间为5秒。同样可以用future.get(),不设置执行超时时间取得结果
                        } catch (InterruptedException e) {
                        } catch (ExecutionException e) {
                        } catch (TimeoutException e) {
                        } finally {
                            executor.shutdown();
                        }
                        BigDecimal a = new BigDecimal(dis);
                        BigDecimal b = new BigDecimal(1000);
                        BigDecimal c = a.divide(b);
                        double dist = c.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        if(dist>999){
                            continue;
                        }
                        String sql_1="insert into distance(position,hotel,distance,score, comments,price,type) " +
                                "values(\""+start+"\",\""+end+"\",\""+dist+"\",\""
                                +score+"\",\""+comments+"\",\""+price+"\",\""
                                +type+"\")";
                        PreparedStatement pr = con.prepareStatement(sql);
                        int d=pr.executeUpdate(sql_1);
                        System.out.println(k);
                        System.out.println(dist);
                        k++;
                    }
                    catch (Exception e){
                        continue;
                    }
                }
            }
        }
        catch(ClassNotFoundException e)
        {
            System.out.println(e);
            System.out.println("驱动程序类找不到");
        }
        catch(SQLException e1)
        {
            System.out.println(e1);
        }
        catch (Exception e){
            System.out.println(e);
        }
    }

    private static String getLonLat(String address){
        //返回输入地址address的经纬度信息, 格式是 经度,纬度
        String queryUrl = "http://restapi.amap.com/v3/geocode/geo?key=5a6ed75cb0f9bd6556fa8382ca14bfee&address="+address;
        String queryResult = getResponse(queryUrl);  //高德接品返回的是JSON格式的字符串

        JSONObject jo = new JSONObject().fromObject(queryResult);
        JSONArray ja = jo.getJSONArray("geocodes");
        return new JSONObject().fromObject(ja.getString(0)).get("location").toString();
    }

    private static Integer getDistance(String startLonLat, String endLonLat){

        //返回起始地startAddr与目的地endAddr之间的距离,单位:米
        int result = 0;
        String queryUrl = "http://restapi.amap.com/v3/distance?key=5a6ed75cb0f9bd6556fa8382ca14bfee&origins="+startLonLat+"&destination="+endLonLat;
        String queryResult = getResponse(queryUrl);
        JSONObject jo = new JSONObject().fromObject(queryResult);
        JSONArray ja = jo.getJSONArray("results");

        result = Integer.parseInt(new JSONObject().fromObject(ja.getString(0)).get("distance").toString());
        return result;
//        return queryResult;
    }

    private static String getResponse(String serverUrl){
        //用JAVA发起http请求,并返回json格式的结果
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(serverUrl);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String line;
            while((line = in.readLine()) != null){
                result.append(line);
            }
            in.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    public static ArrayList<String> readF1(String filePath) throws IOException {
        ArrayList<String> positions = new ArrayList<String>();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                new FileInputStream(filePath)));

        for (String line = br.readLine(); line != null; line = br.readLine()) {
            positions.add(line);
//            System.out.println(line);
        }
        br.close();
        return positions;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值