• 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.

Mostrando entradas con la etiqueta numero. Mostrar todas las entradas
Mostrando entradas con la etiqueta numero. Mostrar todas las entradas

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:

Primos en un arreglo

Ahora buscaremos numeos primos en un arreglo es sencillo ya rapido solo refrescaremos que primo es aquel divisible sobre si y el 1.
/*
 * Realizar el programa que asigne a un arreglo lineal n numeros enteros
 * se pide calcular e imprimir cuantos numeros primos existen en el arreglo.
 */
package arreglos;

/**
 *
 * @author Jonathan
 */
public class arreglos1{

    public static void main(String[] args) {
        int n, i, cnp = 0, res;
        n = (int) (Math.random() * 100);
        int num[] = new int[n + 1];
        for (i = 0; i < n; i++) {
            num[i] = (int) (Math.random() * 100);
            res = 0;
            for (int j = 1; j <= num[i]; j++) {
                if (num[i] % j == 0) {
                    res++;
                }
            }
            if (res == 2) {
                cnp++;
                System.out.println("numero primo =" + num[i]);
            }

        }
        System.out.println("La cantidad de numeros primos es :" + cnp);
    }
}
Ya vimos un unidimensional tenemos la idea apliquemos al bidimensional.
/* 
* Realizar el programa que asigne aleatoriamente a un arreglo bidimensional 
* de mxn elementos datos de tipo entero, se pide calcular e imprimir cuantos 
* nùmeros primos existen en cada fila y en cada columna del arreglo. 
*/ 
package arreglos;

public class arreglos2{

    public static void main(String[] args) {
        int m, n, i, j, cnp, res;
        m = (int) (Math.random() * 10 + 2);
        n = (int) (Math.random() * 10 + 2);
        int beta[][] = new int[m + 1][n + 1];
        cnp = 0;
        for (i = 0; i < m; i++) {
            for (j = 0; j < n; j++) {
                beta[i][j] = (int) (Math.random() * 100);
                res = 0;
                for (int k = 1; k <= beta[i][j]; k++) {
                    if (beta[i][j] % k == 0) {
                        res++;
                    }
                }
                if (res == 2) {
                    cnp++;
                    System.out.println("numero primo =" + beta[i][j]);
                }

            }
        }//Fin de la generacion de filas
        System.out.println("La cantidad de numeros primos en la fila " + i + " son:" + cnp);
        for (j = 0; j < n; j++) {
            for (i = 0; i < m; i++) {
                beta[i][j] = (int) (Math.random() * 100);
                res = 0;
                for (int k = 1; k <= beta[i][j]; k++) {
                    if (beta[i][j] % k == 0) {
                        res++;
                    }
                }
                if (res == 2) {
                    cnp++;
                    System.out.println("numero primo =" + beta[i][j]);
                }

            }
        } //Fin de la generacion de columnas

        System.out.println("La cantidad de numeros primos en la columna " + j + " son:" + cnp);
    }
}
http://www.mediafire.com/?mgtybdwnjmb
Share:

Visitantes

Flag Counter

Popular Posts

Etiquetas

Recent Posts