Advertisement
rajeshinternshala

Untitled

Nov 30th, 2023
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.49 KB | None | 0 0
  1.     public static int getVoteCount(String cityName, int estimatedCost) {
  2.         try {
  3.             // Build the URL
  4.             String urlString = "https://jsonmock.hackerrank.com/api/food_outlets?city=" + cityName + "&estimated_cost=" + estimatedCost;
  5.             URL url = new URL(urlString);
  6.  
  7.             // Open a connection
  8.             HttpURLConnection con = (HttpURLConnection) url.openConnection();
  9.             con.setRequestMethod("GET");
  10.  
  11.             // Read the response
  12.             BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
  13.             String inputLine;
  14.             StringBuilder content = new StringBuilder();
  15.             while ((inputLine = in.readLine()) != null) {
  16.                 content.append(inputLine);
  17.             }
  18.             in.close();
  19.  
  20.             // Parse JSON response manually
  21.             String response = content.toString();
  22.  
  23.             // Check if data array is empty
  24.             if (response.contains("\"data\":[]")) {
  25.                 return -1;
  26.             }
  27.  
  28.             // Regex to find votes
  29.             Pattern pattern = Pattern.compile("\"votes\":(\\d+)");
  30.             Matcher matcher = pattern.matcher(response);
  31.             int totalVotes = 0;
  32.             while (matcher.find()) {
  33.                 totalVotes += Integer.parseInt(matcher.group(1));
  34.             }
  35.  
  36.             return totalVotes;
  37.  
  38.         } catch (Exception e) {
  39.             e.printStackTrace();
  40.             return -1;
  41.         }
  42.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement