Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static int getVoteCount(String cityName, int estimatedCost) {
- try {
- // Build the URL
- String urlString = "https://jsonmock.hackerrank.com/api/food_outlets?city=" + cityName + "&estimated_cost=" + estimatedCost;
- URL url = new URL(urlString);
- // Open a connection
- HttpURLConnection con = (HttpURLConnection) url.openConnection();
- con.setRequestMethod("GET");
- // Read the response
- BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
- String inputLine;
- StringBuilder content = new StringBuilder();
- while ((inputLine = in.readLine()) != null) {
- content.append(inputLine);
- }
- in.close();
- // Parse JSON response manually
- String response = content.toString();
- // Check if data array is empty
- if (response.contains("\"data\":[]")) {
- return -1;
- }
- // Regex to find votes
- Pattern pattern = Pattern.compile("\"votes\":(\\d+)");
- Matcher matcher = pattern.matcher(response);
- int totalVotes = 0;
- while (matcher.find()) {
- totalVotes += Integer.parseInt(matcher.group(1));
- }
- return totalVotes;
- } catch (Exception e) {
- e.printStackTrace();
- return -1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement