Commit b5a738e0 by Patryk Czarnik

switch expression i ładniejsze komunikaty

parent 6023d5a7
...@@ -13,6 +13,10 @@ import javax.servlet.http.HttpServletResponse; ...@@ -13,6 +13,10 @@ import javax.servlet.http.HttpServletResponse;
public class Kalkulator2 extends HttpServlet { public class Kalkulator2 extends HttpServlet {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// doGet wykona się po raz pierwszy, gdy wejdziemy pod adres Kalkulator2
// i wyświetli pusty formularz (wtedy parametry są nullami i nie wchodzimy do ifa)
// i wykona się po raz drugi po naciśnięciu guzika Oblicz i wysłaniu zapytania z parametrami
// - wtedy już wejdziemy do if-a i wyświetlimy wynik
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html"); response.setContentType("text/html");
response.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
...@@ -47,25 +51,19 @@ public class Kalkulator2 extends HttpServlet { ...@@ -47,25 +51,19 @@ public class Kalkulator2 extends HttpServlet {
try { try {
long liczba1 = Long.parseLong(param1); long liczba1 = Long.parseLong(param1);
long liczba2 = Long.parseLong(param2); long liczba2 = Long.parseLong(param2);
long wynik; long wynik = switch(operacja) {
switch(operacja) { case "+" -> liczba1 + liczba2;
case "+": wynik = liczba1 + liczba2; case "-" -> liczba1 - liczba2;
break; case "*" -> liczba1 * liczba2;
case "-": wynik = liczba1 - liczba2; case "/" -> liczba1 / liczba2;
break; default -> throw new IllegalArgumentException("Nieznane działanie: " + operacja);
case "*": wynik = liczba1 * liczba2; };
break; out.printf("<div class='wynik'>%d %s %d = <strong>%d</strong></div>\n",
case "/": wynik = liczba1 / liczba2; liczba1, operacja, liczba2, wynik);
break;
default:
throw new IllegalArgumentException("Nieznane działanie: " + operacja);
}
out.println("<div class='wynik'>Suma: " + wynik + "</div>");
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
out.println("<div class='error'>Niepoprawny format liczby</div>"); out.printf("<div class='error'>Niepoprawny format liczby</div>\n");
} catch(Exception e) { } catch(Exception e) {
out.println("<div class='error'>Błąd: " + e.getMessage() + "</div>"); out.printf("<div class='error'>Błąd: %s</div>\n", e.getMessage());
} }
} }
out.println("</body>"); out.println("</body>");
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment