Está usted en Indice > Construcción > Lenguajes > Java > Lecciones y Paso a Paso > Cómo crear una clase en Java que lea desde el teclado
Construcción
Maletín
Utilidades
Cursos
Promoción
Rentabilidad
Zona Novatos
Foros
Acceso a tu cuenta

Cómo crear una clase en Java que lea desde el teclado (2)

Para datos enteros cortos:

public static short readShort() {
try {
return Short.parseShort(readStr());
} catch(NumberFormatException e) {
return Short.MIN_VALUE;
}
}

Para datos Enteros:

public static short readInt() {
try {
return Integer.parseInt(readStr());
} catch(NumberFormatException e) {
return Integer.MIN_VALUE;
}
}

Para datos enteros largos:

public static short readLong() {
try {
return Long.parseLong(readStr());
} catch(NumberFormatException e) {
return Long.MIN_VALUE;
}
}

Para datos de punto flotante:

public static float readFloat() {
try {
Float f = new Float(readStr());
return f.floatValue();
} catch(NumberFormatException e){
return Float.NaN;
}
}

public static float readDouble() {
try {
Double d = new Double(readStr());
return d.doubleValue();
} catch(NumberFormatException e){
return Double.NaN;
}
}

Ahora si, si unimos estos métodos con la clase anterior, nuestra clase estará completa, quedando de la siguiente manera.

import java.io.*;
public class readData {
public static String readStr() {
String sdato = "";
try{
BufferedReader readIn = new BufferedReader(new InputStreamReader(System.in));
sdato = readIn.readLine();
} catch( IOException e) {
System.err.println("Error: " + e.getMessage());
}
return sdato;
}
public static short readShort() {
try {
return Short.parseShort(readStr());
} catch(NumberFormatException e) {
return Short.MIN_VALUE;
}
}
public static short readInt() {
try {
return Integer.parseInt(readStr());
} catch(NumberFormatException e) {
return Integer.MIN_VALUE;
}
}
public static short readLong() {
try {
return Long.parseLong(readStr());
} catch(NumberFormatException e) {
return Long.MIN_VALUE;
}
}
public static float readFloat() {
try {
Float f = new Float(readStr());
return f.floatValue();
} catch(NumberFormatException e){
return Float.NaN;
}
}
public static float readDouble() {
try {
Double d = new Double(readStr());
return d.doubleValue();
} catch(NumberFormatException e){
return Double.NaN;
}
}
}




Autor: Fredy Ramirez Porfirio
http://www.mygnet.com/articulos/java/50/

Usuarios que han visto este tema también han visto...

- Los operadores en Java
- Centrar una ventana en la pantalla
- Enviando emails con formato texto y HTML en Java
- Introducción a las Java Server Pages
- La fecha en un JSP


Versión imprimible - Versión imprimible de este documento
Enviar e-mail - Enviar por e-mail este documento
Publicidad

Información legal | Política de Privacidad | Contacte con nosotros

Otro proyecto de Factoría de Internet. Copyright© 2003-2008 Factoría de Internet S.L.. Todos los derechos reservados.


Página generada el 05-09-2008 a las 21:43:18