SoloCodigo

Programación General => Java => Mensaje iniciado por: Tuplado en Jueves 27 de Diciembre de 2012, 16:00

Título: Duda_con condicion if
Publicado por: Tuplado en Jueves 27 de Diciembre de 2012, 16:00
Hola buenas tardes.

Estoy haciendo un emulador de cajero con Java y me ha surgido una duda en un condicional if dentro de un método.

Me explico mejor entro por consola un numero, lo transformo a String y calculo la longitud de la String y me da un numero, según el tamaño de la misma.

Efectuo if (cadena == 20) // y no me cumple esta condición.

Adjunto los dos archivos el Main, y el de los metodos.

METODO MAIN
=========
Código: [Seleccionar]
package cuenta;

public class Cuenta {
    public static String name;
    public static String convert;
    public static long account; 
   

    // METODO MAIN
    public static void main(String[] args) {
      // INSTANCIA DEL CONTRUCTOR DATOS 
      CuentaAcciones datos = new CuentaAcciones(name, account,convert); 
      datos.introducirNombre(name);
      datos.introducirCuenta(account);
}
       
    }

CLASE DE LOS METODOS
================
Código: [Seleccionar]
package cuenta;

import javax.swing.JOptionPane.*;
import java.awt.Toolkit;
import java.util.InputMismatchException;
import java.util.Scanner;

public class CuentaAcciones {  // CLASE PRINCIPAL

    // ATRIBUTOS DE LA CLASE
    private long cuenta;
    private String convierteNumeroCadena;
    private String nombre;


    // CONSTRUCTOR DE DATOS BANCARIOS
    public CuentaAcciones(String nombre, long cuenta, String convierteNumeroCadena){
        this.nombre = nombre;
        this.cuenta = cuenta;
        this.convierteNumeroCadena = convierteNumeroCadena;
    }
 
// METODOS   
void introducirNombre(String nombre){
    Scanner teclado = new Scanner(System.in); // CAPTURA DEL TECLADO   
// DECLARACION DE VARIABLE TIPO STRING
boolean esCadena = false; // OBLIGA A ENTRAR AL BUCLE WHILE

while (esCadena==false){ // BUCLE WHILE

 // IMPRIME NOTAS ACLARATORIAS PARA EL USUARIO 
 System.out.println("    INSTRUCCIONES DE USO"       );
 System.out.println("-------------------------------");
 System.out.println("_El nombre va sin acentos y sin ");
 System.out.println(" sin excederse de 15 caracteres ");
 System.out.println("-------------------------------\n");
 
 // IMPRIME DATOS BANCARIOS
 System.out.println("=======================" ); 
 System.out.println("*** DATOS BANCARIOS ***" );
 System.out.println("=======================" );
 
 // NOMBRE DEL USUARIO
 System.out.print("Introduzca su nombre: ");
 nombre=teclado.next();

 // (MATCHES)INCLUYE LETRAS MAYUSCULAS Y MINUSCULAS Y ESPACIOS EN BLANCO
 // Y LA LONGITUD DE CADENA NO PUEDE SER SUPERIOR A 26 CARACTERES
if (nombre.matches("[[a-z]A-Z]*") && (nombre.length() <= 15)){
  System.out.println("Hola "+nombre);
  esCadena = true; // SALE DEL BUCLE
}
     
else{
    System.err.println("¡Error al introducir el nombre!"); // SALIDA POR CONSOLA
    Toolkit.getDefaultToolkit().beep();  // ESTO GENERA UN BEEP
  esCadena = false; // SE MANTIENE EN EL BUCLE
}

}
   
}
void introducirCuenta(long cuenta){
 boolean esNumero = false; 
while (esNumero==false){
   
try{
    Scanner tecladoCuenta= new Scanner(System.in);
    System.out.println("[ENTIDAD ] [OFICINA] [DIGITOS DE CONTROL] [Nº CUENTA]");
    System.out.println("[4 DIGIT ] [4 DIGIT] [     2 DIGIT      ] [10 DIGIT ]");
    System.out.print("Introduzca su numero de cuenta bancaria: ");
    cuenta=tecladoCuenta.nextLong();
   
        this.convierteNumeroCadena = String.valueOf(cuenta);
        System.out.println(convierteNumeroCadena.length());
        long cadena = convierteNumeroCadena.length();
       
    if (convierteNumeroCadena.length() == 20){ // NO SE PQ NO SE CUMPLE ESTO 
      esNumero = true;
      System.out.println("Su numero de cuenta es: "+this.convierteNumeroCadena);
    }
    else{
      System.err.println("¡Error al introducir el numero de cuneta!"); // SALIDA POR CONSOLA
      Toolkit.getDefaultToolkit().beep();  // ESTO GENERA UN BEEP
      esNumero = false;
    }
}

catch (InputMismatchException e)
{
    System.err.println("¡Error al introducir el numero de cuneta!"); // SALIDA POR CONSOLA
    Toolkit.getDefaultToolkit().beep();  // ESTO GENERA UN BEEP
    esNumero = false;
}
}}}
Título: Re:Duda_con condicion if
Publicado por: .net en Jueves 27 de Diciembre de 2012, 21:38
Pues en tus clases encontre cuando llamas al teclado la variable cuenta esta declarada como long por que no la cambias como String en la clase CuentaAcciones, la razon porqur no entra es por que marca una exception ya que el tipo de dato long no soporta un numero tan grande de cuenta...

 Te posteo las clases corregidas

Cuenta class

Código: [Seleccionar]
public class Cuenta {
  public static String name;
    public static String convert;
    public static String account;
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
//       
       
       
      CuentaAcciones datos = new CuentaAcciones(name, account,convert); 
      datos.introducirNombre(name);
      datos.introducirCuenta(account);
    }



Código: [Seleccionar]
import javax.swing.JOptionPane.*;
import java.awt.Toolkit;
import java.util.InputMismatchException;
import java.util.Scanner;

public class CuentaAcciones {  // CLASE PRINCIPAL

    // ATRIBUTOS DE LA CLASE
    private String cuenta;
    private String convierteNumeroCadena;
    private String nombre;


    // CONSTRUCTOR DE DATOS BANCARIOS
    public CuentaAcciones(String nombre, String cuenta, String convierteNumeroCadena){
        this.nombre = nombre;
        this.cuenta = cuenta;
        this.convierteNumeroCadena = convierteNumeroCadena;
    }
 
// METODOS   
void introducirNombre(String nombre){
    Scanner teclado = new Scanner(System.in); // CAPTURA DEL TECLADO   
// DECLARACION DE VARIABLE TIPO STRING
boolean esCadena = false; // OBLIGA A ENTRAR AL BUCLE WHILE

while (esCadena==false){ // BUCLE WHILE

 // IMPRIME NOTAS ACLARATORIAS PARA EL USUARIO 
 System.out.println("    INSTRUCCIONES DE USO"       );
 System.out.println("-------------------------------");
 System.out.println("_El nombre va sin acentos y sin ");
 System.out.println(" sin excederse de 15 caracteres ");
 System.out.println("-------------------------------\n");
 
 // IMPRIME DATOS BANCARIOS
 System.out.println("=======================" ); 
 System.out.println("*** DATOS BANCARIOS ***" );
 System.out.println("=======================" );
 
 // NOMBRE DEL USUARIO
 System.out.print("Introduzca su nombre: ");
 nombre=teclado.next();

 // (MATCHES)INCLUYE LETRAS MAYUSCULAS Y MINUSCULAS Y ESPACIOS EN BLANCO
 // Y LA LONGITUD DE CADENA NO PUEDE SER SUPERIOR A 26 CARACTERES
if (nombre.matches("[[a-z]A-Z]*") && (nombre.length() <= 15)){
  System.out.println("Hola "+nombre);
  esCadena = true; // SALE DEL BUCLE
}
     
else{
    System.err.println("¡Error al introducir el nombre!"); // SALIDA POR CONSOLA
    Toolkit.getDefaultToolkit().beep();  // ESTO GENERA UN BEEP
  esCadena = false; // SE MANTIENE EN EL BUCLE
}

}
   
}
void introducirCuenta(String cuenta){
 boolean esNumero = false; 
while (esNumero==false){
   
try{
    Scanner tecladoCuenta= new Scanner(System.in);
    System.out.println("[ENTIDAD ] [OFICINA] [DIGITOS DE CONTROL] [Nº CUENTA]");
    System.out.println("[4 DIGIT ] [4 DIGIT] [     2 DIGIT      ] [10 DIGIT ]");
    System.out.print("Introduzca su numero de cuenta bancaria: ");
    cuenta=tecladoCuenta.next();
   
        this.convierteNumeroCadena = String.valueOf(cuenta);
        System.out.println(convierteNumeroCadena.length());
        long cadena = convierteNumeroCadena.length();
       
    if (convierteNumeroCadena.length() == 20){ // NO SE PQ NO SE CUMPLE ESTO 
      esNumero = true;
      System.out.println("Su numero de cuenta es: "+this.convierteNumeroCadena);
    }
    else{
      System.err.println("¡Error al introducir el numero de cuneta!"); // SALIDA POR CONSOLA
      Toolkit.getDefaultToolkit().beep();  // ESTO GENERA UN BEEP
      esNumero = false;
    }
}

catch (InputMismatchException e)
{
    System.err.println("¡Error al introducir el numero de cuneta!"); // SALIDA POR CONSOLA
    Toolkit.getDefaultToolkit().beep();  // ESTO GENERA UN BEEP
    esNumero = false;
}
}}}

Verificalas si te sirvio..
Título: Re:Duda_con condicion if
Publicado por: Tuplado en Lunes 7 de Enero de 2013, 21:37
Feliz Año ante todo.
Disculpame .net, he estado super liado con estas fiestas, sii me sirvio le cambie un par de cosas más y lo termine, de todos modos te lo paso, por si le puedes ver algo más para mejorar.

Te estaba mandando el código del programa entero, pero me excede las lineas y no me deja.

Gracias por la ayuda .net un saludo
Título: Re:Duda_con condicion if
Publicado por: arielb en Martes 8 de Enero de 2013, 14:54
Si es mucho el código pegalo acá en http://pastie.org/ o http://pastebin.com/ y colocas acá el url