• This is default featured slide 1 title

    Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by NewBloggerThemes.com.

  • This is default featured slide 2 title

    Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by NewBloggerThemes.com.

  • This is default featured slide 3 title

    Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by NewBloggerThemes.com.

  • This is default featured slide 4 title

    Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by NewBloggerThemes.com.

  • This is default featured slide 5 title

    Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by NewBloggerThemes.com.

Usar Zoom en imagenes

Alguna ves quisiste darle zoom a una imagen o quisiste agregar esa función a un proyecto tuyo pues ahora te traigo la solución.
Se trata de una clase o librería x decirlo asi que te dará esa habilidad.

package Zoom;

/**
 *
 * @author JONATHAN
 */
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;

public class Zoom extends JPanel {

    private Image FOTO_ORIGINAL;
    private Image FOTO_tmp;
    private BufferedImage Imagen_en_memoria;
    private Graphics2D g2D;
    private boolean con_foto = false;   

    private int valEscalaX=0;
    private int valEscalaY=0;

    /* al crear el objeto se crea con una imagen pasada como parametro*/
    public Zoom(BufferedImage f){
        this.FOTO_ORIGINAL = f;
        this.FOTO_tmp = f;
        this.setSize(f.getWidth(),f.getHeight());
        this.setVisible(true);
        this.con_foto=true;
    }

    @Override
    protected void paintComponent(Graphics g) {
      Graphics2D g2 = (Graphics2D)g;
      if(this.con_foto){
        Imagen_en_memoria = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB);
        g2D = Imagen_en_memoria.createGraphics();
        g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        //se añade la foto
        g2D.drawImage(FOTO_tmp,0, 0, FOTO_tmp.getWidth(this), FOTO_tmp.getHeight(this), this);
        g2.drawImage(Imagen_en_memoria, 0, 0, this);
      }
    }

    public void Aumentar(int Valor_Zoom){
        //se calcula el incremento
        valEscalaX =  (int) (FOTO_tmp.getWidth(this) * escala(Valor_Zoom) );
        valEscalaY =  (int) (FOTO_tmp.getHeight(this) * escala(Valor_Zoom) );
        //se escala la imagen sumado el nuevo incremento
        this.FOTO_tmp = FOTO_tmp.getScaledInstance((int) (FOTO_tmp.getWidth(this) + valEscalaX), (int) (FOTO_tmp.getHeight(this) + valEscalaY), Image.SCALE_AREA_AVERAGING);
        resize();
    }

    public void Disminuir(int Valor_Zoom){
        valEscalaX =  (int) (FOTO_tmp.getWidth(this) * escala(Valor_Zoom) );
        valEscalaY =  (int) (FOTO_tmp.getHeight(this) * escala(Valor_Zoom) );
        this.FOTO_tmp = FOTO_tmp.getScaledInstance((int) (FOTO_tmp.getWidth(this) - valEscalaX), (int) (FOTO_tmp.getHeight(this) - valEscalaY), Image.SCALE_AREA_AVERAGING);
        resize();
     }

    private float escala(int v){
        return  v/100f;
    }

    public void Restaurar(){
        this.FOTO_tmp = this.FOTO_ORIGINAL;
        resize();
    }

    private void resize(){
        this.setSize(FOTO_tmp.getWidth(this),FOTO_tmp.getHeight(this));
    }
}
Ahora los métodos para operar esta clase son los siguientes en este caso con este abrilos la imagen en un jpanel que estará dentro de un jscrollpane.
El motivo es para que la imagen al dimensionarse en el jpanel no dimensione tambien el jframe que se usara para visualizar el contenido

private void Abrir_Imagen() {
        fileChooser = new JFileChooser();
        fileChooser.setFileFilter(filter);
        fileChooser.setCurrentDirectory(Directorio);
        int result = fileChooser.showOpenDialog(null);
        if (result == JFileChooser.APPROVE_OPTION) {
            try {
                BufferedImage imagen = ImageIO.read(fileChooser.getSelectedFile());
                Cambiar(imagen.getWidth(), imagen.getHeight());
                zoom = new Zoom(imagen);
                this.Panel.removeAll();
                this.Panel.add(zoom);
                this.Panel.repaint();
                this.Directorio = fileChooser.getCurrentDirectory();
            } catch (IOException ex) {
                System.out.println("error: " + ex);
            }
        }
    }
    private void Cambiar(int alto, int ancho) {
        Panel.setPreferredSize(new Dimension(alto, ancho));
        Panel.setSize(alto, ancho);
    }
Ahora como dije zoom nos permitirá aumentar como disminuir entonces se necesitan estos métodos también.

zoom.Aumentar(50);
zoom.Disminuir(50);
zoom.Restaurar();
Donde 50 en ambos casos es el valor a aumentar o disminuir con respecto a su imagen y bueno restaurar es para regresar a las dimensiones anteriores u originales.
Share:

Coneccion SQL SERVER Y PHP 5.3.x con Netbeans


Hola aun no creo esta entrada pero tengo un ejemplo de como conectar sql server 2008 con php5 fue realizado por mi autoria para un trabajo de la universidad con base de datos espero comentarios acerca de su creación.

Share:

Aplicación multi-lenguaje uso de Java y Properties

El archivo Properties puede servirnos tambien para crear aplicaciones multilenguaje, por ejemplo guardar en cada archivo la estructura del idioma que utilizamos y en otros archivos el lenguaje al que deseamos traducir nuestra aplicacion, osea:

Creamos los archivos .Properties para cada lenguaje.
Para el idioma español podemos tener:



//esto formatea el codigo java
# Idioma español
#

#titulo aplicacion
titulo=Aplicación Multilenguaje

!Datos personales
titulo_datos=Datos Personales
nombre=Nombre:
Apellidos=Apellidos:
mail=Correo Electronico:
dir=Dirección:
fono=Telefono:

#salir
salir=Salir

! menu
archivo=Archivo
nuevo=Nuevo
abrir=Abrir...
guardar=Guardar como...
!Salir

herramientas=Herramientas
es=Español
en=Ingles

ayuda=Ayuda
enlinea=Ayuda en linea...
acerca=Acerca de...

Y para el ingles:
# Idioma Ingles
#
#

#titulo aplicacion
titulo=Multilingual Application

!Datos personales
titulo_datos=Personal Data
nombre=First Name:
Apellidos=Last Name:
mail=Your Email:
dir=Address:
fono=Phone:

#salir
salir=Exit

! menu
archivo=File
nuevo=New
abrir=Open...
guardar=Save as...
!Salir

herramientas=Tools
es=Spanish
en=English

ayuda=Help
enlinea=Online Help...
acerca=About..

Como puede verse, la cantidad de elementos en ambos archivos propeties, es la misma, asi tambien el KEY para cada parametro tambien es la misma, solo cambia el contenido de estos, uno en español y otro en ingles.

Nos creamos una clase para cargar estos archivos:
import java.io.IOException;
import java.util.Properties;

public class NProperties extends Properties{

    public NProperties(String idioma){
        if(idioma.equals("ES")){//español
            getProperties("_ES.properties");
        }else if(idioma.equals("EN")){//Ingles
            getProperties("_EN.properties");
        }else{//sino por default idioma español
            getProperties("ES");
        }
    }

    /* se leen las propiedades */
     private void getProperties(String idioma) {
        try {                
            this.load( getClass().getResourceAsStream(idioma) );
        } catch (IOException ex) {            
        }
   }

}
Share:

Convertir números a texto en java

//esto formatea el codigo java
import java.util.regex.Pattern;
/**
 * @web http://jonathan-palomino.blogspot.com/
 */
public class Numero_Letra {

    private final String[] UNIDADES = {"", "un ", "dos ", "tres ", "cuatro ", "cinco ", "seis ", "siete ", "ocho ", "nueve "};
    private final String[] DECENAS = {"diez ", "once ", "doce ", "trece ", "catorce ", "quince ", "dieciseis ",
        "diecisiete ", "dieciocho ", "diecinueve", "veinte ", "treinta ", "cuarenta ",
        "cincuenta ", "sesenta ", "setenta ", "ochenta ", "noventa "};
    private final String[] CENTENAS = {"", "ciento ", "doscientos ", "trecientos ", "cuatrocientos ", "quinientos ", "seiscientos ",
        "setecientos ", "ochocientos ", "novecientos "};

   public Numero_Letra() {
   }

    public String Convertir(String numero, boolean mayusculas) {
        String literal = "";
        String parte_decimal;    
        //si el numero utiliza (.) en lugar de (,) -> se reemplaza
        numero = numero.replace(".", ",");
        //si el numero no tiene parte decimal, se le agrega ,00
        if(numero.indexOf(",")==-1){
            numero = numero + ",00";
        }
        //se valida formato de entrada -> 0,00 y 999 999 999,00
        if (Pattern.matches("\\d{1,9},\\d{1,2}", numero)) {
            //se divide el numero 0000000,00 -> entero y decimal
            String Num[] = numero.split(",");            
            //de da formato al numero decimal
            parte_decimal = Num[1] + "/100 Bolivianos.";
            //se convierte el numero a literal
            if (Integer.parseInt(Num[0]) == 0) {//si el valor es cero
                literal = "cero ";
            } else if (Integer.parseInt(Num[0]) > 999999) {//si es millon
                literal = getMillones(Num[0]);
            } else if (Integer.parseInt(Num[0]) > 999) {//si es miles
                literal = getMiles(Num[0]);
            } else if (Integer.parseInt(Num[0]) > 99) {//si es centena
                literal = getCentenas(Num[0]);
            } else if (Integer.parseInt(Num[0]) > 9) {//si es decena
                literal = getDecenas(Num[0]);
            } else {//sino unidades -> 9
                literal = getUnidades(Num[0]);
            }
            //devuelve el resultado en mayusculas o minusculas
            if (mayusculas) {
                return (literal + parte_decimal).toUpperCase();
            } else {
                return (literal + parte_decimal);
            }
        } else {//error, no se puede convertir
            return literal = null;
        }
    }

    /* funciones para convertir los numeros a literales */

    private String getUnidades(String numero) {// 1 - 9
        //si tuviera algun 0 antes se lo quita -> 09 = 9 o 009=9
        String num = numero.substring(numero.length() - 1);
        return UNIDADES[Integer.parseInt(num)];
    }

    private String getDecenas(String num) {// 99                        
        int n = Integer.parseInt(num);
        if (n < 10) {//para casos como -> 01 - 09
            return getUnidades(num);
        } else if (n > 19) {//para 20...99
            String u = getUnidades(num);
            if (u.equals("")) { //para 20,30,40,50,60,70,80,90
                return DECENAS[Integer.parseInt(num.substring(0, 1)) + 8];
            } else {
                return DECENAS[Integer.parseInt(num.substring(0, 1)) + 8] + "y " + u;
            }
        } else {//numeros entre 11 y 19
            return DECENAS[n - 10];
        }
    }

    private String getCentenas(String num) {// 999 o 099
        if( Integer.parseInt(num)>99 ){//es centena
            if (Integer.parseInt(num) == 100) {//caso especial
                return " cien ";
            } else {
                 return CENTENAS[Integer.parseInt(num.substring(0, 1))] + getDecenas(num.substring(1));
            } 
        }else{//por Ej. 099 
            //se quita el 0 antes de convertir a decenas
            return getDecenas(Integer.parseInt(num)+"");            
        }        
    }

    private String getMiles(String numero) {// 999 999
        //obtiene las centenas
        String c = numero.substring(numero.length() - 3);
        //obtiene los miles
        String m = numero.substring(0, numero.length() - 3);
        String n="";
        //se comprueba que miles tenga valor entero
        if (Integer.parseInt(m) > 0) {
            n = getCentenas(m);           
            return n + "mil " + getCentenas(c);
        } else {
            return "" + getCentenas(c);
        }

    }

    private String getMillones(String numero) { //000 000 000        
        //se obtiene los miles
        String miles = numero.substring(numero.length() - 6);
        //se obtiene los millones
        String millon = numero.substring(0, numero.length() - 6);
        String n = "";
        if(millon.length()>1){
            n = getCentenas(millon) + "millones ";
        }else{
            n = getUnidades(millon) + "millon ";
        }
        return n + getMiles(miles);        
    }
}

Esta clase, recibe un numero de 0,00 a 999999999.00 en formato String, el separador decimal puede ser un punto (.) o una coma (,), ademas tiene un parametro booleano "mayusculas" el cual sea verdadero (true) o falso (false), retorna el resultado en mayusculas o minusculas, esta clase no acepta numeros negativos ni tampoco numero mayores o iguales a mil millones, aunque claro trate de escribir esta clase para que sea facilmente comprensible y asi pueda ser ampliado o modificado segun sus necesidades.

La forma de llamara a esta clase es:
Numero_Letra NumLetra = new Numero_Letra();
String numero = "20004.70";
System.out.println( numero  + " literal = "  + NumLetra.Convertir(numero,true));
Share:

Algoritmo Julio Cesar (Criptografia)

Este es un algoritmo sencillo consiste en alterar con un intervalo numérico menor a 10 la posición ascii tanto para encriptar o desencriptar.

Por ejemplo a en ascii es 97 pero con un intervalo de 1 se imprimiría un ascii 98 que es b
//esto formatea el codigo java
public class cesar {

private String tabla = "abcdefghijklmnopqrstuvwxyzáéíóú 1234567890@.,;:-+*/$#¿?!¡=()[]{}";

    public cesar(){
    }

    public String Encriptar(String t, int key){
        String texto = LimpiarCadena(t);
        //aqui se almacena el resultado
        String res = "";
        for(int i = 0; i < texto.length();i++)
        {
            //busca la posicion del caracter en la variable tabla
            int pos = tabla.indexOf(texto.charAt(i));
            //realiza el reemplazo
            if ((pos + key) < tabla.length()){
                res = res + tabla.charAt(pos+key);
            }
            else
            {
                res = res + tabla.charAt((pos+key) - tabla.length());
            }
        }
        return res;
    }

    public String Desencriptar(String t, int key){
        String texto = LimpiarCadena(t);
        String res = "";
        for(int i = 0; i < texto.length();i++)
        {
            int pos = tabla.indexOf(texto.charAt(i));
            if ((pos - key) < 0){
                res = res + tabla.charAt((pos-key) + tabla.length());
            }
            else
            {
                res = res + tabla.charAt(pos-key);
            }
        }
        return res;
    }

    private String LimpiarCadena(String t){
        //transforma el texto a minusculas
        t = t.toLowerCase();
        //eliminamos todos los retornos de carro
        t = t.replaceAll("\n", "");
        //eliminamos caracteres prohibidos
        for(int i = 0; i < t.length();i++)
        {
            int pos = tabla.indexOf(t.charAt(i));
            if (pos == -1){
                t = t.replace(t.charAt(i), ' ');
            }
        }
        return t;
    }
}
Ahora la forma de instanciarlo es asi:
cesar cesar = new cesar();
String cadena_final = cesar.Encriptar(texto_inicial, intervalo);
String cadena_inicial= cesar.Desencriptar(cadena_final, intervalo);
Share:

Uso de taryicon o icono de reloj

Hola alguna ves quisieron una aplicación que se minimizara a la barra de reloj osea un segundo plano con Trayicon logramos esto sencillamente agregamos a este modulo lo que necesitamos y listo ademas haremos uso de un PopupMenu para visualizar opciones de dicho programa.

Adjunto el código para que lo usen.
//esto formatea el codigo java
import java.awt.*;
import java.awt.event.*;
import javax.swing.ImageIcon;
public class EjemploSystemTray {
    public EjemploSystemTray() {
        //se declara el objeto tipo icono
        final TrayIcon iconoSystemTray;
        //se verifica que el SystemTray sea soportado
        if (SystemTray.isSupported()) {
            //se obtiene una instancia estática de la clase SystemTray
            SystemTray tray = SystemTray.getSystemTray();
            //esta es la imagen de icono que esta en la misma carpeta que las clases
            ImageIcon icono = new ImageIcon(EjemploSystemTray.class.getResource("CARITA.PNG"));
            //este listener nos permite capturar cualquier tipo de evento
            //que se haga con el mouse sobre el icono
            MouseListener mouseListener = new MouseListener() {
                public void mouseClicked(MouseEvent e) {
                    System.out.println("Icono del System Tray - Mouse clicked!");
                }
                public void mouseEntered(MouseEvent e) {
                    System.out.println("Icono del System Tray - Mouse entered!");
                }
                public void mouseExited(MouseEvent e) {
                    System.out.println("Icono del System Tray - Mouse exited!");
                }
                public void mousePressed(MouseEvent e) {
                    System.out.println("Icono del System Tray - Mouse pressed!");
                }
                public void mouseReleased(MouseEvent e) {
                    System.out.println("Icono del System Tray - Mouse released!");
                }
            };
            //este listener se asociara con un item del menu contextual
            //que aparece al hacer click derecho sobre el icono
            ActionListener escuchadorSalir = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Saliendo...");
                    System.exit(0);
                }
            };
            //menu que aparece al hacer click derecho
            PopupMenu popup = new PopupMenu();
            MenuItem item = new MenuItem("Exit");
            item.addActionListener(escuchadorSalir);
            popup.add(item);
            //iniciamos el objeto TrayIcon
            iconoSystemTray = new TrayIcon(icono.getImage(), "Prueba System Tray", popup);
            //este tipo de listener captura el doble click sobre el icono
            ActionListener accionMostrarMensaje = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    iconoSystemTray.displayMessage("Titulo mensaje",
                            "Este es el contenido del mensaje!",
                            TrayIcon.MessageType.INFO);
                }
            };

            iconoSystemTray.setImageAutoSize(true);
            iconoSystemTray.addActionListener(accionMostrarMensaje);
            iconoSystemTray.addMouseListener(mouseListener);

            //se debe capturar una excepción en caso que falle la adicion de un icono
            try {
                tray.add(iconoSystemTray);
            } catch (AWTException e) {
                System.err.println("No es posible agregar el icono al System Tray");
            }
        }
        else
            System.err.println("Tu sistema no soporta el System Tray :(");
    }
    public static void main(String[] args) {
        new EjemploSystemTray();
    }
}
Share:

SUDOKU

Bueno hace tiempo vi por ahí que preguntaban como hacer un SUDOKU bueno les traigo las respuesta y en código java como tiene que ser es una aplicación de consola que pronto pasara a frame pero por lo pronto disfrútenla.
Son libres de hacer lo que deseen con el codigo:



//codigo java
/**
 *
 * @author JONATHAN
 */
import java.io.*;
import java.util.*;
import java.lang.*;
import java.math.*;

public class SUDOKU {
 
 //PROPIEDADES.
 public static int nivel = 1;
 
 
 //METODO PARA CARGAR JUEGO.
 public static int[][] cargar_juego( int nivel){
  
  int[][] matriz = new int[9][9];
  
  switch (nivel){
  
  case 2:
  
  matriz[0][0] = 7;matriz[0][4] = 5;matriz[0][6] = 4;matriz[1][0] = 4;
  matriz[1][3] = 1;matriz[1][4] = 9;matriz[1][6] = 6;matriz[1][7] = 2;
  matriz[1][8] = 7;matriz[2][2] = 6;matriz[2][8] = 9;matriz[3][0] = 9;
  matriz[3][2] = 3;matriz[3][6] = 8;matriz[4][3] = 4;matriz[4][5] = 3;
  matriz[5][2] = 8;matriz[5][6] = 5;matriz[5][8] = 2;matriz[6][0] = 5;
  matriz[6][6] = 2;matriz[7][0] = 2;matriz[7][1] = 9;matriz[7][2] = 1;
  matriz[7][4] = 4;matriz[7][5] = 7;matriz[7][8] = 8;matriz[8][2] = 7;
  matriz[8][4] = 1;matriz[8][8] = 5;
  
  break;
  
  
  case 1:
  default:
  
  matriz[0][2] = 9;matriz[0][5] = 8;matriz[0][6] = 5; matriz[0][7] = 4;
  matriz[1][8] = 7;matriz[2][1] = 5;matriz[2][2] = 4; matriz[2][4] = 9;
  matriz[2][6] = 1;matriz[3][5] = 6;matriz[3][6] = 3; matriz[3][7] = 2;
  matriz[4][1] = 8;matriz[4][2] = 2;matriz[4][6] = 4; matriz[4][7] = 1;
  matriz[5][1] = 3;matriz[5][2] = 5;matriz[5][3] = 2; matriz[6][2] = 7;
  matriz[6][4] = 3;matriz[6][6] = 2;matriz[6][7] = 5; matriz[7][0] = 9;
  matriz[8][1] = 4;matriz[8][2] = 3;matriz[8][3] = 8; matriz[8][7] = 9;
  
  break;
  
  }
  
  return matriz;
 }
 
 //METODO PARA NO SOBREESCRIBIR VALORES EN EL JUEGO.
 public static boolean es_origen( int fila, int columna, int[][] matriz ){
  
  boolean resultado = false;
  if ( matriz[fila][columna] != 0)
   resultado = true;
  
  return resultado;
  
 }
 
 //METODO QUE DETECTA SI EL JUEGO FUE TERMINADO.
 public static boolean terminado( int[][] matriz ){
  
  boolean resultado = true;
  
  for ( int f = 0; f < matriz.length; f ++)
   for ( int c = 0; c < matriz[0].length; c ++)
    if ( matriz[f][c] == 0 )
     resultado = false;
  
   
  return resultado;

 }
 
 //METODO QUE IMPRIME UN MENSAJE CON BORDE.
 public static void mensaje ( String mensaje ){
  
  //CABECERA.
  System.out.print("É");
  for(int i = 0; i < (mensaje.length() + 20); i ++ )
   System.out.print ("Í");
  System.out.print ("»\n");

  //CUERPO.
  System.out.print("º          ");
  System.out.print( mensaje );
  System.out.print("          º\n");
 
  //PIE
  System.out.print("È");
  for(int i = 0; i < (mensaje.length() + 20); i ++ )
   System.out.print ("Í");
   
  System.out.print ("¼\n\n");
   
  
 }
 
 //METODO QUE IMPRIME EL VECTOR.
 public static void imprime_vector ( int[][] matriz ){
  
  
  System.out.println( " °°°°°°°°°°°°²°°°°°°°°°°°²°°°°°°°°°°°° " );
  
  for ( int f = 0; f < matriz.length; f ++ ){
  
   System.out.print(" ° ");
   
   for ( int c = 0; c < matriz.length; c++){
    
    if ( matriz[f][c] != 0 ) 
     System.out.print ( matriz[f][c] );
    else 
     System.out.print (" ");
    
    if ( es_origen( f, c, cargar_juego( nivel ) ) )
     System.out.print (" ");
    else
     System.out.print (" ");
    
    if ( c == 2 || c == 5) 
     System.out.print ("² ");
    else
     System.out.print ("° ") ;
     
   }
   System.out.println();
   if ( f != 2 && f != 5)
    System.out.print( " °°°°°°°°°°°°²°°°°°°°°°°°²°°°°°°°°°°°° " );
   else
    System.out.print( " ²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²² " );
   System.out.println();
  }
 }

 //METODO PARA COMPROBAR FILAS.
 public static boolean existe_fila( int numero, int fila, int[][] matriz ){
  
  boolean resultado = false;
  
  for ( int i = 0; i < matriz.length; i ++ )
   if ( matriz[(fila-1)][i] == numero ){
     resultado = true;
     break;
   }
   
  //COMPROBAMOS SI ES 0.
  if ( numero == 0 ) resultado = false;
  
  return resultado;
  
 }
 
 //METODO PARA COMPROBAR COLUMNAS.
 public static boolean existe_columna( int numero, int columna, int[][] matriz ){
  
  boolean resultado = false;
  
  for ( int i = 0; i < matriz.length; i ++ )
   if ( matriz[i][(columna-1)] == numero ){
     resultado = true;
     break;
   }
   
  //COMPROBAMOS SI ES 0.
  if ( numero == 0 ) resultado = false;
  
  return resultado;
  
 }
 
 // METODO PARA COMPROBAR LOS INDICES.
 public static boolean comprobar_indice ( int indice ){
  
  if ( indice > 0 && indice < 10)
   return true;
  else
   return false;
  
 }
 
 // METODO PARA COMPROBAR LOS VALORES.
 public static boolean comprobar_valor ( int valor ){
  
  if ( valor >= 0 && valor < 10)
   return true;
  else
   return false;
  
 }
 
 //METODO PARA COMPROBAR LAS CAJAS.
 public static boolean existe_caja ( int valor, int fila, int columna, int[][] matriz ){
  
  //VARIABLES.
  int minimo_fila;
  int maximo_fila;
  int minimo_columna;
  int maximo_columna;
  boolean resultado = false;
 
  //DETERMINAMOS LAS FILAS DE LA CAJA.
  if ( fila > 0 && fila < 4){
   minimo_fila = 0;
   maximo_fila = 2;
  }else if ( fila > 3 && fila < 7 ){
   minimo_fila = 3;
   maximo_fila = 5;
  }else{
   minimo_fila = 6;
   maximo_fila = 8;
  }
    
  //DETERMINAMOS LAS COLUMNAS DE LA CAJA.
  if ( columna > 0 && columna < 4){
   minimo_columna = 0;
   maximo_columna = 2;
  }else if ( columna > 3 && columna < 7 ){
   minimo_columna = 3;
   maximo_columna = 5;
  }else{
   minimo_columna = 6;
   maximo_columna = 8;
  }
  
  //RECORREMOS EL RANGO DE LA CAJA, Y BUSCAMOS EL VALOR.
  for ( int f = minimo_fila; f <= maximo_fila; f++ )
   for ( int c = minimo_columna; c <= maximo_columna; c++)
    if ( matriz[f][c] == valor ){
     resultado = true;
     break; 
     
    }
   
   
  //COMPROBAMOS SI ES 0.
  if ( valor == 0 ) resultado = false;
  
  //REGRESAMOS EL VALOR BOOLEANO.
  return resultado;
   
 
  
 }
 
 //METODO PRINCIPAL
 public static void main ( String[] args ) throws Exception
 {
  
  //VARIABLES.
  BufferedReader teclado = new BufferedReader( new InputStreamReader ( System.in ) );
  int[][] sudoku = new int[9][9];
  int fila = 0;
  int columna = 0;
  int valor = 0;
  
  //CARGAMOS EL JUEGO.
  sudoku = cargar_juego( nivel );
   
  while ( true ){
  
  //IMPRIMIMOS EL VECTOR.
  imprime_vector ( sudoku );
  
  //PEDIMOS LOS DATOS.
  System.out.println( "Inserte las coordenadas (fila/columna): " );
  
  //FILA.
  System.out.print( "[fila]: " );
  fila = Integer.parseInt( teclado.readLine() );
  
  //COLUMNA.
  System.out.print( "[columna]: " );
  columna = Integer.parseInt( teclado.readLine() );
  
  //VALOR.
  System.out.print( "[valor]: " );
  valor = Integer.parseInt( teclado.readLine() );
  
  //COMPROBAMOS LA FILA ESTA EN RANGO.
  if ( !comprobar_indice(fila) )
   mensaje ("El valor de la fila no es correcto..");
  
  //COMPROBAMOS LA COLUMNA ESTA EN RANGO.
  else if ( !comprobar_indice(columna) )
   mensaje ( "El valor de la columna no es correcto.");
   
  //COMPROBAMOS QUE EL VALOR ESTA EN RANGO.
  else if ( !comprobar_valor(valor) )
   mensaje ( "El valor introducido no es valido..");
   
  //COMPROBAMOS QUE USE CASILLAS DISPONIBLES.
  else if ( es_origen( (fila - 1), (columna - 1), cargar_juego( nivel ) ) )
   mensaje ( "Ese valor es predeterminado del juego...");
   
  //COMPRUEBA QUE NO SE REPITA EL VALOR EN LA FILA.
  else if ( existe_fila( valor, fila, sudoku ) )
   mensaje ("[X] El valor " + valor + " ya ha sido usado en la fila..");
   
  //COMPRUEBA QUE NO SE REPITA EL VALOR EN LA COLUMNA..
  else if ( existe_columna( valor, columna, sudoku ) )
   mensaje ( "[X] El valor " + valor + " ya ha sido usado en la columna..");
   
  //COMPRUEBA QUE EL VALOR NO ESTÉ EN LA CAJA.
  else if ( existe_caja( valor, fila, columna, sudoku ) )
   mensaje ( "[X] El valor ya existe en la caja..");
   
  //INTRODUCIMOS EL VALOR A LA MATRIZ.
  else {
   sudoku[(fila - 1)][(columna - 1)] = valor;
   mensaje( "[" + fila + "," + columna + "]=" + valor + " Correcto.");
  }
  
  
  //COMPRUEBA SI SE TERMINÓ EL JUEGO.
  if ( terminado( sudoku ) ){
   mensaje( "FELICIDADES!!!! HAS TERMINADO EL JUEGO!!");
   imprime_vector( sudoku );
   System.out.println ( "Presiona una tecla para continuar en el siguiente nivel..");
   teclado.readLine();
   
   //AUMENTAMOS EL NIVEL DEL JUEGO.
   nivel ++;
   sudoku = cargar_juego( nivel );
   mensaje( "SUDOKU NIVEL " + nivel );
  }
 
 
  }
 
 } 

 
}


Share:

Visitantes

Flag Counter

Popular Posts

Etiquetas

Recent Posts