Advertisement
Guest User

Clase Datos JAVIER GARCIA ICETA

a guest
Jun 4th, 2017
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.24 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package elecciones;
  7. import java.sql.*;
  8.  
  9. /**
  10.  *
  11.  * @author alumno
  12.  */
  13. public class Datos {
  14.     String[] partidos = {"AHI", "PP", "PSOE", "NC", "IU", "POD"};
  15.     //votos totales de los partidos. Se corresponden con los índices de los partidos en el array partidos.
  16.     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
  17.     //"tabla" con los resultados de la operación de la Ley D'Hont
  18.     int[][] dhont = new int[partidos.length][6];
  19.     //array con los resultados del reparto de consejeros
  20.     int[] resultado = {0, 0, 0, 0, 0, 0};
  21.    
  22.     //Atributos relacionados con SQL
  23.     Connection conexion = null;
  24.     Statement stmt = null;
  25.    
  26.     public Datos(){}  
  27.    
  28.     /*--------------------------------CONEXION---------------------------------*/
  29.    
  30.     public Connection abrirConexion(String user, String password){
  31.         String cadenaConexion;
  32.        
  33.         try{
  34.             cadenaConexion = "jdbc:sqlserver://;databaseName=elecciones;user="+user+";password="+password;
  35.             Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
  36.             conexion = DriverManager.getConnection(cadenaConexion);
  37.             stmt = conexion.createStatement();
  38.         }catch(ClassNotFoundException | SQLException e){
  39.             System.out.println("Error de conexión:\n"+e.getMessage());
  40.         }
  41.        
  42.         return conexion;
  43.     }
  44.    
  45.     public boolean conexionCorrecta(String u, String p){
  46.         abrirConexion(u, p);
  47.         boolean esCorrecto = false;
  48.        
  49.         if(conexion != null)
  50.             esCorrecto = true;
  51.        
  52.         return esCorrecto;
  53.     }
  54.    
  55.     public void cerrarConexion(){
  56.         try{
  57.             if(conexion != null)
  58.                 conexion.close();
  59.             if(stmt != null)
  60.                 stmt.close();
  61.         }catch(Exception e){
  62.             System.out.println("Error al cerrar la conexión.");
  63.         }
  64.     }
  65.    
  66.     //método que extrae los votos de la tabla en la base de datos y los asigna al array correspondiente
  67.     public void obtenerTotalVotos(){
  68.         try{
  69.             //la consulta extrae el total de votos y el código del partido en la tabla
  70.             String consulta="select sum(numVotos), (select nombre from partidos as p where cod=codPartido)" +
  71.                             " from votos" +
  72.                             " group by codPartido";
  73.             Statement stmt=conexion.createStatement();
  74.             ResultSet rs=stmt.executeQuery(consulta);
  75.                
  76.             while(rs.next()){
  77.                 for (int i = 0; i < totales.length; i++) {
  78.                     //comprobar que el partido está en el array y asignar la suma de votos al array de totales con la misma posición
  79.                     if(rs.getString(2).equalsIgnoreCase(partidos[i])){
  80.                         totales[i]=rs.getInt(1);
  81.                     }
  82.                 }
  83.             }
  84.         }catch(Exception e){
  85.             System.out.println("error");
  86.         }
  87.     }
  88.     /*-------------------------------------------------------------------------*/
  89.    
  90.     //método que rellena la tabla aplicando la Ley D'Hont
  91.     public void rellenarDhont(){
  92.         int iteracion; //variable que controla el número por el que se debe dividir
  93.         for(int i=0; i<dhont.length; i++){
  94.             iteracion = 1;
  95.             for(int j=0; j<dhont[0].length; j++){
  96.                 dhont[i][j] = totales[i]/iteracion;
  97.                 iteracion++;
  98.             }
  99.         }
  100.     }
  101.    
  102.     public int getFilaVotado(){
  103.         //las variables fila y columna sirven para poner a 0 el valor encontrado, y también fila es el valor buscado que se devolverá
  104.         int fila = 0;
  105.         int columna = 0;
  106.         int mayor = dhont[0][0]; //se le asigna el primer valor de forma arbitraria
  107.        
  108.         for(int i=0; i<dhont.length; i++){
  109.             for(int j=0; j<dhont[0].length; j++){
  110.                 if(dhont[i][j] > mayor){
  111.                     mayor = dhont[i][j];
  112.                     fila = i;
  113.                     columna = j;
  114.                 }
  115.             }
  116.         }
  117.         dhont[fila][columna] = 0;
  118.        
  119.         return fila;
  120.     }
  121.    
  122.     //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
  123.     public void addVoto(int fila){
  124.         resultado[fila]++;
  125.     }
  126.    
  127.     public void calcularResultados(int numConsejeros){
  128.         rellenarDhont();
  129.         for(int i=0; i<numConsejeros; i++){
  130.             addVoto(getFilaVotado());
  131.         }
  132.     }
  133.    
  134.    
  135.     /*----------- MÉTODOS toString -------------*/
  136.    
  137.     public String partidosToString(){
  138.         String salida = "";
  139.        
  140.         for(int i=0; i<partidos.length; i++){
  141.             salida += partidos[i];
  142.             salida += " ";
  143.         }
  144.        
  145.         return salida;
  146.     }
  147.    
  148.     public String totalesToString(){
  149.         String salida = "";
  150.        
  151.         for(int i=0; i<totales.length; i++){
  152.             salida += totales[i];
  153.             salida += " ";
  154.         }
  155.        
  156.         return salida;
  157.     }
  158.    
  159.     public String dhontToString(){
  160.         String salida = "";
  161.        
  162.         for(int i=0; i<dhont.length; i++){
  163.             for(int j=0; j<dhont[0].length; j++){
  164.                 salida += dhont[i][j];
  165.                 salida += "\t";
  166.             }
  167.             salida += "\n";
  168.         }
  169.        
  170.         return salida;
  171.     }
  172.    
  173.     public String resultadoToString(){
  174.         String salida = "";
  175.        
  176.         for(int i=0; i<resultado.length; i++){
  177.             salida += resultado[i];
  178.             salida += " ";
  179.         }
  180.        
  181.         return salida;
  182.     }
  183.    
  184.     @Override
  185.     public String toString(){
  186.         String salida = "";
  187.        
  188.         salida += "Partido\t\tTotal\t\tConsejeros\n";
  189.         for(int i=0; i<partidos.length; i++){
  190.             salida += partidos[i] + "\t\t" + totales[i] + "\t\t" + resultado[i] + "\n";
  191.         }
  192.        
  193.         return salida;
  194.     }
  195. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement