Overview
This page provides a comprehensive reference for all classes, methods, and code structures in the Currency Converter application.
ConversorApp (Main Controller)
Package: lad.com.alura.conversormoneda.controladores
Purpose: Application entry point and main controller that orchestrates the conversion flow.
Class Structure
package lad.com.alura.conversormoneda.controladores;
import lad.com.alura.conversormoneda.modelos.ConsultaMoneda;
import lad.com.alura.conversormoneda.vista.Conversor;
import lad.com.alura.conversormoneda.modelos.RegistroConversion;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ConversorApp {
public static void main ( String [] args ) {
// Implementation
}
}
main() Method
Command-line arguments (not used in current implementation)
Complete Implementation
Main Method
Currency Selection Logic
public static void main ( String [] args) {
Scanner sc = new Scanner ( System . in );
// Instantiate service (OOP)
ConsultaMoneda consulta = new ConsultaMoneda ();
// Create history list
List < RegistroConversion > historial = new ArrayList <>();
int opcion ;
while ( true ) {
// Display menu
Conversor . eleccionUserMenu ();
opcion = sc . nextInt ();
if (opcion == 8 ) {
System . out . println ( "Gracias por usar el conversor." );
break ;
}
if (opcion == 7 ) {
// Display history
System . out . println ( " \n --- HISTORIAL DE CONVERSIONES ---" );
if ( historial . isEmpty ()) {
System . out . println ( "No hay conversiones recientes." );
} else {
historial . forEach ( System . out :: println); // Lambda!
}
System . out . println ( "--------------------------------- \n " );
continue ;
}
if (opcion >= 1 && opcion <= 6 ) {
// Process conversion...
} else {
System . out . println ( "Opción no válida. Intente de nuevo. \n " );
}
}
sc . close ();
}
System . out . println ( "Ingrese el valor que desea convertir: " );
double cantidad = sc . nextDouble ();
double resultado ;
String base = "" , objetivo = "" ;
// Assign currencies based on option
objetivo = switch (opcion) {
case 1 -> {
base = "USD" ;
yield "ARS" ;
}
case 2 -> {
base = "ARS" ;
yield "USD" ;
}
case 3 -> {
base = "USD" ;
yield "BRL" ;
}
case 4 -> {
base = "BRL" ;
yield "USD" ;
}
case 5 -> {
base = "USD" ;
yield "COP" ;
}
case 6 -> {
base = "COP" ;
yield "USD" ;
}
default -> objetivo;
};
// Use the service to get the rate
resultado = consulta . obtenerTasa (base, objetivo, cantidad);
System . out . println ( "El valor es: " + resultado + " [" + objetivo + "] \n " );
// Save to history with current timestamp
RegistroConversion registro = new RegistroConversion (
base, objetivo, cantidad, resultado, LocalDateTime . now ()
);
historial . add (registro);
Key Features
Menu Options
Options 1-6: Currency conversions
Option 7: View history
Option 8: Exit application
Data Structures
Scanner for user input
ConsultaMoneda service instance
List<RegistroConversion> for history
Switch Expressions Uses Java 14+ switch expressions with yield for cleaner code
Lambda Functions Uses method reference System.out::println for history display
ConsultaMoneda (Service Class)
Package: lad.com.alura.conversormoneda.modelos
Purpose: Service class responsible for communicating with ExchangeRate-API.
Class Definition
package lad.com.alura.conversormoneda.modelos;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class ConsultaMoneda {
// Instance method (not static)
public double obtenerTasa ( String monedaBase ,
String monedaObjetivo ,
double cantidad ) {
// Implementation
}
}
obtenerTasa() Method Signature
Source currency code (e.g., “USD”, “ARS”, “BRL”)
Target currency code (e.g., “ARS”, “BRL”, “COP”)
Converted amount, or 0 if error occurs
Method Implementation Breakdown
Create HTTP Client
HttpClient cliente = HttpClient . newHttpClient ();
Creates a new HTTP client for making requests
Build API URL
String url = "https://v6.exchangerate-api.com/v6/9ba310889b4d07769a662fc0/pair/"
+ monedaBase + "/" + monedaObjetivo + "/" + cantidad;
Constructs the API endpoint with currency codes and amount
Create HTTP Request
HttpRequest request = HttpRequest . newBuilder ()
. uri ( URI . create (url))
. GET ()
. build ();
Builds an HTTP GET request
Send Request
HttpResponse < String > respuesta = cliente . send (
request,
HttpResponse . BodyHandlers . ofString ()
);
Sends the request and receives response as String
Parse JSON
JsonElement elemento = JsonParser . parseString ( respuesta . body ());
JsonObject objectRoot = elemento . getAsJsonObject ();
Parses JSON response into JsonObject
Extract Result
return objectRoot . get ( "conversion_result" ). getAsDouble ();
Extracts and returns the conversion result
Handle Errors
catch ( Exception e ) {
System . out . println ( "Error al conectar con la API: " + e . getMessage ());
return 0 ;
}
Catches all exceptions and returns 0
Usage Example
// Create service instance
ConsultaMoneda consulta = new ConsultaMoneda ();
// Perform conversion
double resultado = consulta . obtenerTasa ( "USD" , "ARS" , 100.0 );
// Display result
System . out . println ( "100 USD = " + resultado + " ARS" );
The method is not static , following OOP principles. You must create an instance of ConsultaMoneda to use it.
RegistroConversion (Data Record)
Package: lad.com.alura.conversormoneda.modelos
Purpose: Immutable data structure to store conversion history entries.
Record Definition
package lad.com.alura.conversormoneda.modelos;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public record RegistroConversion (
String monedaBase,
String monedaObjetivo,
double cantidad,
double resultado,
LocalDateTime fechaHora
) {
@ Override
public String toString () {
DateTimeFormatter formato = DateTimeFormatter . ofPattern ( "dd-MM-yyyy HH:mm:ss" );
return "[" + fechaHora . format (formato) + "] "
+ cantidad + " " + monedaBase + " =>> "
+ resultado + " " + monedaObjetivo;
}
}
Record Components
The base (source) currency code
The target (destination) currency code
The original amount in base currency
The converted amount in target currency
Timestamp when the conversion was performed
Java Records (Java 14+)
What are Records? Records are a special kind of class introduced in Java 14 that provide:
Automatic constructor
Automatic getters (component methods)
Automatic equals() and hashCode()
Automatic toString() (can be overridden)
Immutability by default
Automatically Generated Methods
Constructor
Getters
equals & hashCode
// Automatically generated canonical constructor
public RegistroConversion (
String monedaBase,
String monedaObjetivo,
double cantidad,
double resultado,
LocalDateTime fechaHora
) {
// Fields are automatically assigned
}
// Component accessor methods (automatically generated)
public String monedaBase () { return this . monedaBase ; }
public String monedaObjetivo () { return this . monedaObjetivo ; }
public double cantidad () { return this . cantidad ; }
public double resultado () { return this . resultado ; }
public LocalDateTime fechaHora () { return this . fechaHora ; }
// Automatically generated based on all components
@ Override
public boolean equals ( Object obj) {
// Compares all fields
}
@ Override
public int hashCode () {
// Hash based on all fields
}
Custom toString() Implementation
The record overrides toString() to provide formatted output:
@ Override
public String toString () {
DateTimeFormatter formato = DateTimeFormatter . ofPattern ( "dd-MM-yyyy HH:mm:ss" );
return "[" + fechaHora . format (formato) + "] "
+ cantidad + " " + monedaBase + " =>> "
+ resultado + " " + monedaObjetivo;
}
Example Output:
[05-03-2026 14:30:45] 100.0 USD =>> 6323.41 ARS
Usage Examples
Creating Records
Accessing Components
Storing in Collections
// Create a new conversion record
RegistroConversion registro = new RegistroConversion (
"USD" , // monedaBase
"ARS" , // monedaObjetivo
100.0 , // cantidad
6323.41 , // resultado
LocalDateTime . now () // fechaHora
);
Conversor (View Class)
Package: lad.com.alura.conversormoneda.vista
Purpose: Handles user interface display and presentation logic.
Class Structure
package lad.com.alura.conversormoneda.vista;
public class Conversor {
public static void eleccionUserMenu () {
System . out . print ( """
Sea bienvenido/a al Conversor de Moneda =]
==================================================
1) Dólar =>> Peso argentino
2) Peso argentino =>> Dólar
3) Dólar =>> Real brasileño
4) Real brasileño =>> Dólar
5) Dólar =>> Peso colombiano
6) Peso colombiano =>> Dólar
7) Historial de conversiones
8) Salir
==================================================
Elija una opción válida:
""" );
}
}
No return value (displays menu to console)
Static method - can be called without creating an instance
Text Blocks (Java 13+)
The method uses text blocks for multi-line string literals:
System . out . print ( """
Multi-line
String
Content
""" );
Benefits: No need for \n newline characters, no need for string concatenation, preserves formatting and indentation, and more readable for large text blocks. System . out . print (
"Sea bienvenido/a al Conversor de Moneda =] \n " +
" \n " +
"================================================== \n " +
"1) Dólar =>> Peso argentino \n " +
"2) Peso argentino =>> Dólar \n " +
// ... more lines
);
Drawbacks: Requires \n for each line, requires + concatenation, less readable, and more error-prone.
Option 1 USD → ARS (Dollar to Argentine Peso)
Option 2 ARS → USD (Argentine Peso to Dollar)
Option 3 USD → BRL (Dollar to Brazilian Real)
Option 4 BRL → USD (Brazilian Real to Dollar)
Option 5 USD → COP (Dollar to Colombian Peso)
Option 6 COP → USD (Colombian Peso to Dollar)
Option 7 Display conversion history
Option 8 Exit the application
Usage
// Call from controller
Conversor . eleccionUserMenu ();
// User sees the menu and enters their choice
int opcion = scanner . nextInt ();
The method uses System.out.print() (not println()) so the cursor remains on the same line as the prompt, providing a better user experience.
Method Signatures Summary
ConversorApp.main() public static void main ( String [] args)
Application entry point - orchestrates the entire conversion flow
ConsultaMoneda.obtenerTasa() public double obtenerTasa ( String monedaBase, String monedaObjetivo, double cantidad)
Performs API request and returns converted amount
RegistroConversion (Constructor) public RegistroConversion ( String monedaBase, String monedaObjetivo,
double cantidad, double resultado,
LocalDateTime fechaHora)
Creates immutable conversion history record
RegistroConversion.toString() Returns formatted string representation of the conversion
Conversor.eleccionUserMenu() public static void eleccionUserMenu ()
Displays the main menu to the user
Modern Java Features Used
Used in RegistroConversion for immutable data carriers: public record RegistroConversion (
String monedaBase,
String monedaObjetivo,
double cantidad,
double resultado,
LocalDateTime fechaHora
) { }
Used in Conversor.eleccionUserMenu() for multi-line strings: System . out . print ( """
Multi-line
String
""" );
Switch Expressions (Java 14+)
Used in ConversorApp.main() for currency selection: objetivo = switch (opcion) {
case 1 -> {
base = "USD" ;
yield "ARS" ;
}
// ...
};
Lambda Expressions (Java 8+)
Used for history display: historial . forEach ( System . out :: println);
Modern HTTP client API: HttpClient cliente = HttpClient . newHttpClient ();
HttpResponse < String > respuesta = cliente . send (request,
HttpResponse . BodyHandlers . ofString ());
While not used in this codebase, could simplify local variable declarations: var consulta = new ConsultaMoneda ();
var historial = new ArrayList < RegistroConversion >();
Java Version Requirement : This application requires Java 14 or higher due to the use of records and switch expressions with yield.
Dependencies
Standard Library
External Libraries
java.net.http.HttpClient - HTTP communication
java.net.URI - URL handling
java.time.LocalDateTime - Timestamp management
java.time.format.DateTimeFormatter - Date formatting
java.util.Scanner - User input
java.util.ArrayList - Dynamic list storage
java.util.List - List interface
Gson 2.10.1+ (com.google.code.gson)
JsonParser - Parse JSON strings
JsonElement - JSON element representation
JsonObject - JSON object access