Ver Mensaje Individual
  #8 (permalink)  
Antiguo 18/03/2005, 15:01
Avatar de stock
stock
 
Fecha de Ingreso: junio-2004
Ubicación: Monterrey NL
Mensajes: 2.390
Antigüedad: 19 años, 10 meses
Puntos: 53
Tema: Capturar desde el teclado en modo consola
Pregunta: Como puedo capturar caracteres desde el teclado en Java??
Respuesta: Las instrucciones System.in.read(); nos permite leer entradas desde el teclado en codigo ASCII, mediante un ciclo capturamos los caracteres introducidos hasta que se presione la tecla ENTER, almacenandolos en un STRING, ya despues, depende lo que necesitemos, lo caovertimos a Integer, Double, etc... basicamente es lo que hace la siguiente clase :)

Código:
import java.io.*;
import java.util.*;

public class MeterDatos
{

    public static String readLine()
    {
        char nextChar;
        String result = "";
        boolean done = false;

        while (!done)
        {
            nextChar = readChar();
            if (nextChar == '\n')
               done = true;
            else if (nextChar == '\r')
            {
                //Do nothing.
                //Next loop iteration will detect '\n'
            }
            else
               result = result + nextChar;
        }

        return result;
    }

    public static String readLineWord()
    {
        String inputString = null,
               result = null;
        boolean done = false;

        while(!done)
        {
            inputString = readLine();
            StringTokenizer wordSource =
                                new StringTokenizer(inputString);
            if (wordSource.hasMoreTokens())
            {
                result = wordSource.nextToken();
                done = true;
            }
            else
            {
                System.out.println("Your input is not correct. Your input must");
                System.out.println("contain at least one nonwhitespace character.");
                System.out.println("Please, try again. Enter input:");
           }
       }

       return result;
   }


    public static int readLineInt()
    {
        String inputString = null;
        int number = -9999;//To keep the compiler happy.
                              //Designed to look like a garbage value.
        boolean done = false;

        while (! done)
        {
            try
            {
                inputString = readLine();
                inputString = inputString.trim();
                number = (Integer.valueOf(inputString).intValue());
                done = true;
            }
            catch (NumberFormatException e)
            {
                System.out.println(
                                "Your input number is not correct.");
                System.out.println("Your input number must be");
                System.out.println("a whole number written as an");
                System.out.println("ordinary numeral, such as 42");
                System.out.println("Please, try again.");
                System.out.println("Enter a whole number:");
            }
        }

        return number;
    }


    public static long readLineLong()
    {
        String inputString = null;
        long number = -9999;//To keep the compiler happy.
                            //Designed to look like a garbage value.
        boolean done = false;

        while (! done)
        {
            try
            {
                inputString = readLine();
                inputString = inputString.trim();
                number = (Long.valueOf(inputString).longValue());
                done = true;
            }
            catch (NumberFormatException e)
            {
                System.out.println(
                                "Your input number is not correct.");
                System.out.println("Your input number must be");
                System.out.println("a whole number written as an");
                System.out.println("ordinary numeral, such as 42");
                System.out.println("Please, try again.");
                System.out.println("Enter a whole number:");
            }
       }

        return number;
    }


    public static double readLineDouble()
    {
        String inputString = null;
        double number = -9999;//To keep the compiler happy.
                              //Designed to look like a garbage value.
        boolean done = false;

        while (! done)
        {
            try
            {
                inputString = readLine();
                inputString = inputString.trim();
                number = (Double.valueOf(inputString).doubleValue());
                done = true;
            }
            catch (NumberFormatException e)
            {
                System.out.println(
                                "Your input number is not correct.");
                System.out.println("Your input number must be");
                System.out.println("an ordinary number either with");
                System.out.println("or without a decimal point,");
                System.out.println("such as 42 or 9.99");
                System.out.println("Please, try again.");
                System.out.println("Enter a whole number:");
            }
        }

        return number;
    }


    public static float readLineFloat()
    {
        String inputString = null;
        float number = -9999;//To keep the compiler happy.
                              //Designed to look like a garbage value.
        boolean done = false;

        while (! done)
        {
            try
            {
                inputString = readLine();
                inputString = inputString.trim();
                number = (Float.valueOf(inputString).floatValue());
                done = true;
            }
            catch (NumberFormatException e)
            {
                System.out.println(
                                "Your input number is not correct.");
                System.out.println("Your input number must be");
                System.out.println("an ordinary number either with");
                System.out.println("or without a decimal point,");
                System.out.println("such as 42 or 9.99");
                System.out.println("Please, try again.");
                System.out.println("Enter a whole number:");
            }
        }

        return number;
    }

    public static char readLineNonwhiteChar()
    {
        boolean done = false;
        String inputString = null;
        char nonWhite = ' ';//To keep the compiler happy.

        while (! done)
        {
            inputString = readLine();
            inputString = inputString.trim();
            if (inputString.length() == 0)
            {
                System.out.println(
                                "Your input is not correct.");
                System.out.println("Your input must contain at");
                System.out.println(
                              "least one nonwhitespace character.");
                System.out.println("Please, try again.");
                System.out.println("Enter input:");
            }
            else
            {
                nonWhite = (inputString.charAt(0));
                done = true;
            }
        }

        return nonWhite;
    }

    public static boolean readLineBoolean()
    {
        boolean done = false;
        String inputString = null;
        boolean result = false;//To keep the compiler happy.

        while (! done)
        {
            inputString = readLine();
            inputString = inputString.trim();
            if (inputString.equalsIgnoreCase("true")
                   || inputString.equalsIgnoreCase("t"))
            {
                result = true;
                done = true;
            }
            else if (inputString.equalsIgnoreCase("false")
                        || inputString.equalsIgnoreCase("f"))
            {
                result = false;
                done = true;
            }
            else
            {
                System.out.println(
                                "Your input number is not correct.");
                System.out.println("Your input number must be");
                System.out.println("one of the following:");
                System.out.println("the word true,");
                System.out.println("the word false,");
                System.out.println("the letter T,");
                System.out.println("or the letter F.");
                System.out.println("You may use either uppercase");
                System.out.println("or lowercase letters.");
                System.out.println("Please, try again.");
                System.out.println("Enter input:");
            }
         }

        return result;
    }

    public static char readChar()
    {
        int charAsInt = -1; //To keep the compiler happy
        try
        {
            charAsInt = System.in.read();
        }
        catch(IOException e)
        {
            System.out.println(e.getMessage());
            System.out.println("Fatal error. Ending Program.");
            System.exit(0);
        }

        return (char)charAsInt;
    }

    public static char readNonwhiteChar()
    {
      char next;

      next =  readChar();
      while (Character.isWhitespace(next))
          next =  readChar();

      return next;
    }

}
compila la clase, si lo notaste los metodos son de tipo "static", entonces, no es necesario creear objeto de esta clase, unicamente pon el archivo .class en la misma carpeta que tu aplicacion.

para usarla solamente seria asi:

String mytext = MeterDatos.readLine();
double myVar = MeterDatos.readLineDouble();
etc....

Última edición por stock; 18/03/2005 a las 15:08