package operaciones; import java.util.ArrayList; import java.util.List; public class Main { /* * args <- [] -> "Excepción." * args <- ["@" "10" "20" "30"] -> "Excepción." * args <- ["+" "10" "@" "20"] -> "Excepción." * args <- ["+" "@" "10" "20"] -> "Excepción." * args <- ["+" "10" "20" "@"] -> "Excepción." * * args <- ["+"] -> "0" * args <- ["*"] -> "1" * args <- ["+" "10" "20" "30" "40" "50"] -> "150" * args <- ["*" "10" "20" "30" "40" "50"] -> "12000000" */ public static void main(String[] args) { Analizador analizador = new Analizador(args); try { analizador.validarParametros(); } catch (ExcepcionParametro e) { System.out.println(e.getMessage()); return; } Ejecutor ejecutor = new Ejecutor(args); ejecutor.realizarOperacion(); System.out.println(ejecutor.getResultado()); } } final class Parametro { private String valor; public Parametro(String valor) { this.valor = valor; } public boolean esOperacion() { return (this.valor.equals("+") || this.valor.equals("*")); } public boolean esNumeroEntero() { try { @SuppressWarnings("unused") int numero = Integer.parseInt(this.valor); }catch (Exception e) { return false; } return true; } public String getValor() { return this.valor; } } final class Analizador { private List parametros = new ArrayList<>(); public Analizador(String[] args) { for (String arg : args) { this.parametros.add(new Parametro(arg)); } } public void validarParametros() throws ExcepcionParametro { if (this.parametros.size() == 0) { throw new ExcepcionParametro("Excepción: No se indico la operación a realizar."); } Parametro primerParametro = this.parametros.get(0); if (!primerParametro.esOperacion()) { throw new ExcepcionParametro("Excepción: '" + primerParametro.getValor() + "' no es una operación válida."); } for (int i = 1; i < this.parametros.size(); i++) { if (!this.parametros.get(i).esNumeroEntero()) { throw new ExcepcionParametro("Excepción: '" + this.parametros.get(i).getValor() + "' no es un número entero."); } } } } final class ExcepcionParametro extends Exception { private String message; public ExcepcionParametro(String message) { this.message = message; } public String getMessage() { return this.message; } } final class Ejecutor { private List parametros = new ArrayList<>(); private int resultado; public Ejecutor(String[] args) { for (String arg : args) { this.parametros.add(new Parametro(arg)); } } public void realizarOperacion() { if (this.parametros.get(0).getValor().equals("+")) { this.resultado = 0; for (int i = 1; i < this.parametros.size(); i++) { this.resultado += Integer.parseInt(this.parametros.get(i).getValor()); } } if (this.parametros.get(0).getValor().equals("*")) { this.resultado = 1; for (int i = 1; i < this.parametros.size(); i++) { this.resultado *= Integer.parseInt(this.parametros.get(i).getValor()); } } } public int getResultado() { return this.resultado; } }