Skip to content

Instantly share code, notes, and snippets.

@jkcgs
Created August 31, 2018 15:54
Show Gist options
  • Save jkcgs/e782c1ce08efd52cdbd528f9369f74a5 to your computer and use it in GitHub Desktop.
Save jkcgs/e782c1ce08efd52cdbd528f9369f74a5 to your computer and use it in GitHub Desktop.
Una cosa que alguien pidió y que yo hice porque estaba aburrido.
package com.makzk;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
/**
* "necesito hacer una wea de codigo en netbeans la cual debe registrar nombres, rut ,inasistencia, monto
* y luego revisar por rut, obteniendo los datos de la persona y los dias de inasistencia con el descuento
* del monto mensual, entendieron? yo tampoco profe qlao, no especifica bien las weas, alguna pagina para
* aprender a hacer esta wea(en general con netbeans)? xd"
*
* - /u/Masuramaru, 2018
* https://www.reddit.com/r/chile/comments/9ao1m1/discusi%C3%B3n_random_semanal/e5516xf/
*
* Por /u/makzk - https://github.com/jkcgs/
*/
public class ProyectoPalSub {
public static void main(String[] args) {
String opt;
int diasMes = 20;
HashMap<String, String[]> data = new HashMap<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
do {
System.out.println("Elije una opción:");
System.out.println("1. Ingresar datos");
System.out.println("2. Buscar datos");
System.out.println("\n0. Salir");
System.out.print("> ");
try {
opt = reader.readLine().trim();
} catch (IOException e) {
e.printStackTrace();
break;
}
if (opt.equals("1")) {
String rut;
String nombre = "";
int diasInasistencia = -1;
float monto = -1;
System.out.println("Ingresa los datos a continuación:");
// Lee el RUT
rut = leerRUT();
if (rut.isEmpty()) {
continue;
}
// Leer nombre
try {
System.out.print("Nombre (dejar en blanco para cancelar): ");
nombre = reader.readLine();
if (nombre.trim().isEmpty()) {
continue;
}
} catch (IOException e) {
e.printStackTrace();
continue;
}
// Leer dias de inasistencia (0 >= n >= diasMes)
do {
try {
System.out.print("Dias de inasistencia: ");
String dias = reader.readLine();
if (!isInteger(dias)) {
System.out.println("Valor incorrecto");
} else if (Integer.parseInt(dias) > diasMes || Integer.parseInt(dias) < 0) {
System.out.println("No puede superar los 20 días ni ser un número negativo");
} else {
diasInasistencia = Integer.parseInt(dias);
}
} catch (IOException e) {
e.printStackTrace();
}
} while(diasInasistencia < 0);
// Leer monto (n > 0)
do {
try {
System.out.print("Monto: ");
String vmonto = reader.readLine();
if (!isFloat(vmonto)) {
System.out.println("Valor incorrecto");
} else if (Float.parseFloat(vmonto) < 0) {
System.out.println("No puede ser un valor negativo");
} else {
monto = Float.parseFloat(vmonto);
}
} catch (IOException e) {
e.printStackTrace();
}
} while(monto < 0);
// Muestra si los datos fueron creados o actualizados si ya existía el RUT en memoria
boolean existe = data.containsKey(rut);
data.put(rut, new String[]{nombre, diasInasistencia+"", monto+""});
System.out.println("Datos " + (existe ? "actualizados" : "guardados"));
} else if (opt.equals("2")) {
// Si no hay datos, no vale la pena mostrar esta opción
if (data.size() == 0) {
System.out.println("No hay datos registrados\n");
continue;
}
// Lee el RUT
String rut = leerRUT();
if (rut.isEmpty()) {
continue;
}
if (!data.containsKey(rut)) {
System.out.println("RUT no registrado\n");
continue;
}
// Mostrar datos si el RUT existe
String[] datos = data.get(rut);
System.out.println("\nRUT: " + formatRUT(rut));
System.out.println("Nombre: " + datos[0]);
System.out.println("Dias inasistencia: " + datos[1]);
System.out.println("Sueldo base: $" + datos[2]);
// Calcular descuento por inasistencia
float dif = (Float.parseFloat(datos[2]) / diasMes) * Integer.parseInt(datos[1]);
System.out.println("Resta por inasistencia: $-" + dif);
System.out.println("Sueldo final: $" + (Float.parseFloat(datos[2]) - dif));
System.out.println("\n");
} else if (!opt.equals("0")) {
System.out.println("Opción incorrecta");
}
} while(!opt.equals("0"));
}
/**
* Lee un RUT hasta que se ingrese un valor correcto, validando el formato y el dígito verificador.
* Si se ingresa un valor vacío, se devuelve este valor vacío.
* @return El RUT leído.
*/
private static String leerRUT() {
String rut;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
do {
System.out.print("RUT (dejar vacío para cancelar): ");
try {
rut = reader.readLine().trim().replaceFirst("0", "");
if (rut.isEmpty()) {
return "";
}
if (!rut.matches("^[0-9]{1,2}(.?[0-9]){3}-?[0-9kK]$") || !validarRut(rut)) {
System.out.println("RUT inválido");
continue;
}
return rut.toUpperCase().replace(".", "").replace("-", "");
} catch (IOException e) {
e.printStackTrace();
}
} while(true);
}
/**
* Valida un RUT
* http://www.qualityinfosolutions.com/validador-de-rut-chileno-en-java/
* @param rut El RUT a validar en formato 11.111.111-1 (puntos y guión son eliminados)
* @return Un valor booleano dependiente de si el RUT es válido o no
*/
private static boolean validarRut(String rut) {
try {
rut = rut.toUpperCase().replace(".", "").replace("-", "");
int rutAux = Integer.parseInt(rut.substring(0, rut.length() - 1));
char dv = rut.charAt(rut.length() - 1);
int m = 0, s = 1;
for (; rutAux != 0; rutAux /= 10) {
s = (s + rutAux % 10 * (9 - m++ % 6)) % 11;
}
return dv == (char) (s != 0 ? s + 47 : 75);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* Valida si una cadena de texto puede ser convertida a entero
* @param val El valor a verificar
* @return Un valor booleano dependiente de la validación realizada
*/
private static boolean isInteger(String val) {
try {
Integer.parseInt(val);
return true;
} catch (NumberFormatException e) {
return false;
}
}
/**
* Valida si una cadena de texto puede ser convertida a número flotante
* @param val El valor a verificar
* @return Un valor booleano dependiente de la validación realizada
*/
private static boolean isFloat(String val) {
try {
Float.parseFloat(val);
return true;
} catch (NumberFormatException e) {
return false;
}
}
/**
* Agrega un guión entre el número del RUT y el dígito verificador
* @param rut El string con el RUT
* @return El string con el guión
*/
private static String formatRUT(String rut) {
String dv = rut.substring(rut.length() - 2);
String number = rut.substring(0, rut.length() - 2);
return number + "-" + dv;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment