Solution-Task 2
EquationSolverunknown
java
a year ago
2.2 kB
2
Indexable
Never
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class EquationSolver { private static final String API_URL = "https://api.mathjs.org/v4/?expr="; public static void main(String[] args) { try (BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in))) { String expression; while (!(expression = inputReader.readLine()).equals("end")) { try { // Evaluate the expression and print the result String result = evaluateExpression(expression); System.out.println(expression + " => " + result); } catch (IOException e) { // Handle any errors that occur during evaluation System.out.println("An error occurred while evaluating the expression: " + expression); e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } } public static String evaluateExpression(String expression) throws IOException { // Encode the expression to make it URL-safe String encodedExpression = URLEncoder.encode(expression, "UTF-8"); // Construct the API URL with the encoded expression String apiUrl = API_URL + encodedExpression; // Open a connection to the API URL HttpURLConnection connection = (HttpURLConnection) new URL(apiUrl).openConnection(); connection.setRequestMethod("GET"); // Get the response code from the API int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // Read the result from the API response try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { return reader.readLine(); } } else { // Handle the case when the API returns an error response throw new IOException("Error response: " + responseCode); } } }