Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package elecciones;
- import java.sql.*;
- /**
- *
- * @author alumno
- */
- public class Datos {
- String[] partidos = {"AHI", "PP", "PSOE", "NC", "IU", "POD"};
- //votos totales de los partidos. Se corresponden con los índices de los partidos en el array partidos.
- int[] totales = new int[6]; //{2708, 820, 1498, 389, 99, 391}; Estos son los valores que se calcularán a través de una consulta SQL
- //"tabla" con los resultados de la operación de la Ley D'Hont
- int[][] dhont = new int[partidos.length][6];
- //array con los resultados del reparto de consejeros
- int[] resultado = {0, 0, 0, 0, 0, 0};
- //Atributos relacionados con SQL
- Connection conexion = null;
- Statement stmt = null;
- public Datos(){}
- /*--------------------------------CONEXION---------------------------------*/
- public Connection abrirConexion(String user, String password){
- String cadenaConexion;
- try{
- cadenaConexion = "jdbc:sqlserver://;databaseName=elecciones;user="+user+";password="+password;
- Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
- conexion = DriverManager.getConnection(cadenaConexion);
- stmt = conexion.createStatement();
- }catch(ClassNotFoundException | SQLException e){
- System.out.println("Error de conexión:\n"+e.getMessage());
- }
- return conexion;
- }
- public boolean conexionCorrecta(String u, String p){
- abrirConexion(u, p);
- boolean esCorrecto = false;
- if(conexion != null)
- esCorrecto = true;
- return esCorrecto;
- }
- public void cerrarConexion(){
- try{
- if(conexion != null)
- conexion.close();
- if(stmt != null)
- stmt.close();
- }catch(Exception e){
- System.out.println("Error al cerrar la conexión.");
- }
- }
- //método que extrae los votos de la tabla en la base de datos y los asigna al array correspondiente
- public void obtenerTotalVotos(){
- try{
- //la consulta extrae el total de votos y el código del partido en la tabla
- String consulta="select sum(numVotos), (select nombre from partidos as p where cod=codPartido)" +
- " from votos" +
- " group by codPartido";
- Statement stmt=conexion.createStatement();
- ResultSet rs=stmt.executeQuery(consulta);
- while(rs.next()){
- for (int i = 0; i < totales.length; i++) {
- //comprobar que el partido está en el array y asignar la suma de votos al array de totales con la misma posición
- if(rs.getString(2).equalsIgnoreCase(partidos[i])){
- totales[i]=rs.getInt(1);
- }
- }
- }
- }catch(Exception e){
- System.out.println("error");
- }
- }
- /*-------------------------------------------------------------------------*/
- //método que rellena la tabla aplicando la Ley D'Hont
- public void rellenarDhont(){
- int iteracion; //variable que controla el número por el que se debe dividir
- for(int i=0; i<dhont.length; i++){
- iteracion = 1;
- for(int j=0; j<dhont[0].length; j++){
- dhont[i][j] = totales[i]/iteracion;
- iteracion++;
- }
- }
- }
- public int getFilaVotado(){
- //las variables fila y columna sirven para poner a 0 el valor encontrado, y también fila es el valor buscado que se devolverá
- int fila = 0;
- int columna = 0;
- int mayor = dhont[0][0]; //se le asigna el primer valor de forma arbitraria
- for(int i=0; i<dhont.length; i++){
- for(int j=0; j<dhont[0].length; j++){
- if(dhont[i][j] > mayor){
- mayor = dhont[i][j];
- fila = i;
- columna = j;
- }
- }
- }
- dhont[fila][columna] = 0;
- return fila;
- }
- //método que añade un voto después de hacer el recuento por la tabla D'Hont. Se le pasa la fila donde está el partido a añadir el voto
- public void addVoto(int fila){
- resultado[fila]++;
- }
- public void calcularResultados(int numConsejeros){
- rellenarDhont();
- for(int i=0; i<numConsejeros; i++){
- addVoto(getFilaVotado());
- }
- }
- /*----------- MÉTODOS toString -------------*/
- public String partidosToString(){
- String salida = "";
- for(int i=0; i<partidos.length; i++){
- salida += partidos[i];
- salida += " ";
- }
- return salida;
- }
- public String totalesToString(){
- String salida = "";
- for(int i=0; i<totales.length; i++){
- salida += totales[i];
- salida += " ";
- }
- return salida;
- }
- public String dhontToString(){
- String salida = "";
- for(int i=0; i<dhont.length; i++){
- for(int j=0; j<dhont[0].length; j++){
- salida += dhont[i][j];
- salida += "\t";
- }
- salida += "\n";
- }
- return salida;
- }
- public String resultadoToString(){
- String salida = "";
- for(int i=0; i<resultado.length; i++){
- salida += resultado[i];
- salida += " ";
- }
- return salida;
- }
- @Override
- public String toString(){
- String salida = "";
- salida += "Partido\t\tTotal\t\tConsejeros\n";
- for(int i=0; i<partidos.length; i++){
- salida += partidos[i] + "\t\t" + totales[i] + "\t\t" + resultado[i] + "\n";
- }
- return salida;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement