package com.mycompany.demo.banregio;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class Main {

    public static long fechaHoy = 0;
    public static double tasaInteres = 7.50;
    public static double tasaIVA = 16.00;
    private static final DecimalFormat df = new DecimalFormat("0.00");
    public static List<Pagos> pagosRealizados = new ArrayList<>();
    public static List<CuentasDebito> cuentasPagos = new ArrayList<>();

    // Entidad Prestamos
    public static class Prestamos {
        private String cliente;
        private int id;
        private Date fecha;
        private double monto;
        private String estado;

        public String getCliente() {
            return this.cliente;
        }

        public void setCliente(String cliente) {
            this.cliente = cliente;
        }

        public int getId() {
            return this.id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public Date getFecha() {
            return this.fecha;
        }

        public void setFecha(Date fecha) {
            this.fecha = fecha;
        }

        public double getMonto() {
            return this.monto;
        }

        public void setMonto(double monto) {
            this.monto = monto;
        }

        public String getEstado() {
            return this.estado;
        }

        public void setEstado(String estado) {
            this.estado = estado;
        }

        public Prestamos(String cliente, int id, Date fecha, double monto, String estado) {
            this.cliente = cliente;
            this.id = id;
            this.fecha = fecha;
            this.monto = monto;
            this.estado = estado;
        }

        @Override
        public String toString() {
            return "Prestamo{" +
                    "cliente='" + cliente + '\'' +
                    ", fecha=" + fecha +
                    ", monto=" + monto +
                    ", estado=" + estado +
                    '}';
        }
    }

    // Entidad CuentasDebito
    public static class CuentasDebito {

        private String cliente;
        private double monto;
        private String estado;

        public String getCliente() {
            return this.cliente;
        }

        public void setCliente(String cliente) {
            this.cliente = cliente;
        }

        public double getMonto() {
            return this.monto;
        }

        public void setMonto(double monto) {
            this.monto = monto;
        }

        public String getEstado() {
            return this.estado;
        }

        public void setEstado(String estado) {
            this.estado = estado;
        }

        public CuentasDebito(String cliente, double monto, String estado) {
            this.cliente = cliente;
            this.monto = monto;
            this.estado = estado;
        }

        @Override
        public String toString() {
            return "CuentaDebito{" +
                    "cliente='" + cliente + '\'' +
                    ", monto=" + monto +
                    '}';
        }

    }

    // Entidad Pagos
    public static class Pagos {
        private String cliente;
        private double plazo;
        private double monto;
        private double interes;
        private double IVA;
        private double montoPago;

        public String getCliente() {
            return this.cliente;
        }

        public void setCliente(String cliente) {
            this.cliente = cliente;
        }

        public double getPlazo() {
            return this.plazo;
        }

        public void setPlazo(double plazo) {
            this.plazo = plazo;
        }

        public double getMonto() {
            return this.monto;
        }

        public void setMonto(double monto) {
            this.monto = monto;
        }

        public double getInteres() {
            return this.interes;
        }

        public void setInteres(double interes) {
            this.interes = interes;
        }

        public double getIVA() {
            return this.IVA;
        }

        public void setIVA(double IVA) {
            this.IVA = IVA;
        }

        public double getMontoPagoo() {
            return this.montoPago;
        }

        public void setMontoPago(double montoPago) {
            this.montoPago = montoPago;
        }

        public Pagos(String cliente, double plazo, double monto, double interes, double montoPago) {
            this.cliente = cliente;
            this.plazo = plazo;
            this.monto = monto;
            this.interes = interes;
            this.montoPago = montoPago;
        }

        @Override
        public String toString() {
            return "Pago{" +
                    "cliente='" + cliente + '\'' +
                    ", plazo=" + plazo +
                    ", monto=" + monto +
                    ", interes=" + interes +
                    ", pago=" + montoPago +
                    '}';
        }
    }

    // Poblar BD de prestamos
    public static List<Prestamos> getPrestamos() {

        Prestamos prestamo1 = new Prestamos("00103228", 1, formatterDate("10-ene-21"), 37500.00, "Pendiente");
        Prestamos prestamo2 = new Prestamos("00103228", 2, formatterDate("19-ene-21"), 725.18, "Pendiente");
        Prestamos prestamo3 = new Prestamos("00103228", 3, formatterDate("31-ene-21"), 1578.22, "Pendiente");
        Prestamos prestamo4 = new Prestamos("00103228", 4, formatterDate("04-feb-21"), 380.00, "Pendiente");

        Prestamos prestamo5 = new Prestamos("70099925", 1, formatterDate("07-ene-21"), 2175.25, "Pagado");
        Prestamos prestamo6 = new Prestamos("70099925", 2, formatterDate("13-ene-21"), 499.99, "Pagado");
        Prestamos prestamo7 = new Prestamos("70099925", 3, formatterDate("24-ene-21"), 5725.18, "Pendiente");
        Prestamos prestamo8 = new Prestamos("70099925", 4, formatterDate("07-feb-21"), 876.13, "Pendiente");

        Prestamos prestamo9 = new Prestamos("00298185", 1, formatterDate("04-feb-21"), 545.55, "Pendiente");
        Prestamos prestamo10 = new Prestamos("15000125", 1, formatterDate("31-dic-20"), 15220.00, "Pendiente");

        List<Prestamos> prestamos = Arrays.asList(prestamo1, prestamo2, prestamo3, prestamo4, prestamo5, prestamo6,
                prestamo7, prestamo8, prestamo9, prestamo10);
        return prestamos;
    }

    // Poblar BD de cuentas débito
    public static List<CuentasDebito> getCuentasDebito() {
        CuentasDebito cuenta1 = new CuentasDebito("00103228", 15375.28, "Activa");
        CuentasDebito cuenta2 = new CuentasDebito("70099925", 3728.51, "Bloqueada");
        CuentasDebito cuenta3 = new CuentasDebito("00298185", 0.00, "Cancelada");
        CuentasDebito cuenta4 = new CuentasDebito("15000125", 235.28, "Activa");

        return Arrays.asList(cuenta1, cuenta2, cuenta3, cuenta4);
    }

    // Metodo para obtener cuentas acyivas
    public static List<CuentasDebito> getCuentasActivas() {
        return getCuentasDebito()
                .stream()
                .filter(cuenta -> cuenta.getEstado().equals("Activa"))
                .collect(Collectors.toList());
    }

    // Metodo para obtener prestamos de una cuenta
    public static List<Prestamos> getPrestamosCuenta(String cliente) {
        return getPrestamos().stream()
                .filter(prestamo -> prestamo.getCliente().equals(cliente))
                .sorted(Comparator.comparing(Prestamos::getFecha))
                .collect(Collectors.toList());
    }

    // Se realiza el pago de los prestamos de las cuentas activas
    public static void realizarPago() {
        List<CuentasDebito> cuentasActivas = getCuentasActivas();
        for (CuentasDebito cuenta : cuentasActivas) {
            // System.out.println(getPrestamosCuenta(cuenta.getCliente()));
            List<Prestamos> prestamosCuenta = getPrestamosCuenta(cuenta.getCliente());
            for (Prestamos prestamo : prestamosCuenta) {
                // RealizarCobro
                realizaCobro(cuenta, prestamo);
            }
        }
    }

    // Metodo que realiza el cobro a la cuenta indicada y actualiza el estatus del
    // préstamo
    public static void realizaCobro(CuentasDebito cuenta, Prestamos prestamo) {
        long plazo = calculoPlazo(prestamo);
        double tasaInteresPorcentaje = (tasaInteres * 100) / prestamo.getMonto();
        double interes = Double.parseDouble(df.format(prestamo.getMonto() * plazo * tasaInteresPorcentaje / 360));
        double iva = Double.parseDouble(df.format(interes * tasaIVA));
        double cobro = prestamo.getMonto() + interes + iva;

        // Se realiza el descuento a la cuenta
        if (cobro <= cuenta.getMonto()) {
            double monto = cuenta.getMonto() - cobro;
            cuenta.setMonto(monto);

            // Se actualiza el estado del préstamo
            prestamo.setEstado("Pagado");

            // Se crea un registro en Pagos
            Pagos pago = new Pagos(cuenta.getCliente(), plazo, monto, interes, cobro);
            pagosRealizados.add(pago);
            cuentasPagos.add(cuenta);
        }
    }

    public static void main(String[] args) throws ParseException {
        // getCuentasActivas().forEach(System.out::println);

        // List<CuentasDebito> cuentas = getCuentasActivas();
        // for (CuentasDebito cuenta : cuentas) {
        // System.out.println(getPrestamosCuenta(cuenta.getCliente()));
        // }

        realizarPago();
        System.out.println("Pagos Realizados");
        System.out.println(pagosRealizados);
        System.out.println("Cuentas de pagos realizados");
        System.out.println(cuentasPagos);

    }

    public static long calculoPlazo(Prestamos prestamo) {
        long fechaPrestamoMilli = prestamo.getFecha().getTime();
        long timeDiff = Math.abs(getFechaEntrada() - fechaPrestamoMilli);
        return TimeUnit.DAYS.convert(timeDiff, TimeUnit.MILLISECONDS);
    }

    public static long getFechaEntrada() {
        Date fechaEntrada;
        try {
            fechaEntrada = new SimpleDateFormat("dd-MMM-yyyy").parse("15-feb-21");
            return fechaEntrada.getTime();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 0;
    }

    public static Date formatterDate(String fecha) {
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
        try {
            return formatter.parse(fecha);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}
 

Java online compiler

Write, Run & Share Java code online using OneCompiler's Java online compiler for free. It's one of the robust, feature-rich online compilers for Java language, running the Java LTS version 17. Getting started with the OneCompiler's Java editor is easy and fast. The editor shows sample boilerplate code when you choose language as Java and start coding.

Taking inputs (stdin)

OneCompiler's Java online editor supports stdin and users can give inputs to the programs using the STDIN textbox under the I/O tab. Using Scanner class in Java program, you can read the inputs. Following is a sample program that shows reading STDIN ( A string in this case ).

import java.util.Scanner;
class Input {
    public static void main(String[] args) {
    	Scanner input = new Scanner(System.in);
    	System.out.println("Enter your name: ");
    	String inp = input.next();
    	System.out.println("Hello, " + inp);
    }
}

Adding dependencies

OneCompiler supports Gradle for dependency management. Users can add dependencies in the build.gradle file and use them in their programs. When you add the dependencies for the first time, the first run might be a little slow as we download the dependencies, but the subsequent runs will be faster. Following sample Gradle configuration shows how to add dependencies

apply plugin:'application'
mainClassName = 'HelloWorld'

run { standardInput = System.in }
sourceSets { main { java { srcDir './' } } }

repositories {
    jcenter()
}

dependencies {
    // add dependencies here as below
    implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
}

About Java

Java is a very popular general-purpose programming language, it is class-based and object-oriented. Java was developed by James Gosling at Sun Microsystems ( later acquired by Oracle) the initial release of Java was in 1995. Java 17 is the latest long-term supported version (LTS). As of today, Java is the world's number one server programming language with a 12 million developer community, 5 million students studying worldwide and it's #1 choice for the cloud development.

Syntax help

Variables

short x = 999; 			// -32768 to 32767
int   x = 99999; 		// -2147483648 to 2147483647
long  x = 99999999999L; // -9223372036854775808 to 9223372036854775807

float x = 1.2;
double x = 99.99d;

byte x = 99; // -128 to 127
char x = 'A';
boolean x = true;

Loops

1. If Else:

When ever you want to perform a set of operations based on a condition If-Else is used.

if(conditional-expression) {
  // code
} else {
  // code
}

Example:

int i = 10;
if(i % 2 == 0) {
  System.out.println("i is even number");
} else {
  System.out.println("i is odd number");
}

2. Switch:

Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.

switch(<conditional-expression>) {    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
...    
    
default:     
 //code to be executed when all the above cases are not matched;    
} 

3. For:

For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations is known in advance.

for(Initialization; Condition; Increment/decrement){  
    //code  
} 

4. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while(<condition>){  
 // code 
}  

5. Do-While:

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {
  // code 
} while (<condition>); 

Classes and Objects

Class is the blueprint of an object, which is also referred as user-defined data type with variables and functions. Object is a basic unit in OOP, and is an instance of the class.

How to create a Class:

class keyword is required to create a class.

Example:

class Mobile {
    public:    // access specifier which specifies that accessibility of class members 
    string name; // string variable (attribute)
    int price; // int variable (attribute)
};

How to create a Object:

Mobile m1 = new Mobile();

How to define methods in a class:

public class Greeting {
    static void hello() {
        System.out.println("Hello.. Happy learning!");
    }

    public static void main(String[] args) {
        hello();
    }
}

Collections

Collection is a group of objects which can be represented as a single unit. Collections are introduced to bring a unified common interface to all the objects.

Collection Framework was introduced since JDK 1.2 which is used to represent and manage Collections and it contains:

  1. Interfaces
  2. Classes
  3. Algorithms

This framework also defines map interfaces and several classes in addition to Collections.

Advantages:

  • High performance
  • Reduces developer's effort
  • Unified architecture which has common methods for all objects.
CollectionDescription
SetSet is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc
ListList is a ordered collection of elements which can have duplicates. Lists are classified into ArrayList, LinkedList, Vectors
QueueFIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue.
DequeDeque(Double Ended Queue) is used to add or remove elements from both the ends of the Queue(both head and tail)
MapMap contains key-values pairs which don't have any duplicates. Map is implemented in HashMap, TreeMap etc.