Sie sind auf Seite 1von 9

La clase Scanner

Vase http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html. La clase Scanner provee un sencillo scanner que puede analizar tipos Java primitivos utilizando expresiones regulares. Un scanner descompone su entrada en tokens utilizando un patrn delimitador, que por defecto es blancos. Los tokens resultantes pueden ser convertidos en diversos tipos de valores usando diversos mtodos next.
next

y hasNext

The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block. A scanner will default to interpreting numbers as decimal unless a different radix has been set by using the useRadix(int) method.

generaciondecodigos@nereida:~/src/groovy/strings$ cat -n UseScanner3.groovy 1 #!/usr/bin/env groovy 2 // On a Java 5 or 6 JVM, Groovy can also make use of Scanners: 3 Scanner sc = new Scanner(new File("myNumbers")); 4 sc.useDelimiter("\\D+") 5 while (sc.hasNext()) { 6 n = sc.next(); 7 println "One more $n" 8 } generaciondecodigos@nereida:~/src/groovy/strings$ cat -n myNumbers 1 123 2 ab 456 3 78910 4 45 generaciondecodigos@nereida:~/src/groovy/strings$ ./UseScanner3.groovy One more 123 One more 456 One more 78910 One more 45
findInLine

The findInLine(java.lang.String), findWithinHorizon(java.lang.String, int), and skip(java.util.regex.Pattern) methods operate independently of the delimiter pattern. These methods will attempt to match the specified pattern with no regard to delimiters in the input and thus can be used in special circumstances where delimiters are not relevant. These methods may block waiting for more input. Esto es lo que dice el manual sobre findInLine:
public String findInLine(Pattern pattern)

Attempts to find the next occurrence of the specified pattern ignoring delimiters. If the pattern is found before the next line separator, the scanner advances past the input that matched and returns the string that matched the pattern. If no such pattern is detected in the input up to the next line separator, then null is returned and the scanner's position is unchanged. This method may block waiting for input that matches the pattern. Since this method continues to search through the input looking for the specified pattern, it may buffer all of the input searching for the desired token if no line separators are present.

Parameters: pattern - the pattern to scan for Returns: the text that matched the specified pattern Throws: IllegalStateException - if this scanner is closed

Veamos un ejemplo:

generaciondecodigos@nereida:~/src/groovy/strings$ cat -n findInLine.groovy 1 instr = "Name: Joe Age: 28 ID: 77"; 2 3 Scanner conin = new Scanner(instr); 4 5 conin.findInLine("Age:"); // find Age 6 7 while (conin.hasNext()) { 8 n = conin.next(); 9 println n 10 } generaciondecodigos@nereida:~/src/groovy/strings$ groovy findInLine.groovy 28 ID: 77
El siguiente ejemplo recoje el match en un objeto:

generaciondecodigos@nereida:~/src/groovy/strings$ cat -n UseScanner.groovy 1 #!/usr/bin/env groovy 2 // On a Java 5 or 6 JVM, Groovy can also make use of Scanners:

3 data = 'hippopotamus means river horse' 4 println data 5 6 s = new Scanner(data) 7 s.findInLine(/(.{5}).{8}(.{5}) (.{5}) (.*)/) 8 m = s.match() 9 println m.groupCount() 10 11 fields = [] 12 (1..m.groupCount()).each{ fields << m.group(it) } 13 14 assert fields == ['hippo', 'means', 'river', 'horse'] 15 println fields generaciondecodigos@nereida:~/src/groovy/strings$ ./UseScanner.groovy hippopotamus means river horse 4 [hippo, means, river, horse]
Locales An instance of this class is capable of scanning numbers in the standard formats as well as in the formats of the scanner's locale. A scanner's initial locale is the value returned by the Locale.getDefault() method; it may be changed via the useLocale(java.util.Locale) method. The localized formats are defined in terms of the following parameters, which for a particular locale are taken from that locale's DecimalFormat object, df, and its and DecimalFormatSymbols object, dfs.

LocalGroupSeparator The character used to separate thousands groups, i.e., dfs.getGroupingSeparator() LocalDecimalSeparator The character used for the decimal point, i.e., dfs.getDecimalSeparator() LocalPositivePrefix The string that appears before a positive number (may be empty), i.e., df.getPositivePrefix() LocalPositiveSuffix The string that appears after a positive number (may be empty), i.e., df.getPositiveSuffix() LocalNegativePrefix The string that appears before a negative number (may be empty), i.e., df.getNegativePrefix()

LocalNegativeSuffix The string that appears after a negative number (may be empty), i.e., df.getNegativeSuffix() LocalNaN The string that represents not-anumber for floating-point values, i.e., dfs.getInfinity() LocalInfinity The string that represents infinity for floating-point values, i.e., dfs.getInfinity()
The strings that can be parsed as numbers by an instance of this class are specified in terms of the following regular-expression grammar, where Rmax is the highest digit in the radix being used (for example, Rmax is 9 in base 10). El siguiente ejemplo lee nmeros en formato espaol de un fichero y los suma:

generaciondecodigos@nereida:~/src/groovy/strings$ cat -n ScanSum.groovy 1 Scanner s = null; 2 sum = 0.0; 3 s = new Scanner(new File("esnumbers.txt")); 4 s.useLocale(Locale.FRANCE); 5 6 while (s.hasNext()) { 7 if (s.hasNextDouble()) { 8 next = s.nextDouble(); 9 sum += next; 10 println "next = $next sum=$sum" 11 } else { 12 s.next(); 13 } 14 } 15 s.close(); 16 17 System.out.println(sum); generaciondecodigos@nereida:~/src/groovy/strings$ cat -n esnumbers.txt 1 3,5 2 4,2 3 83 generaciondecodigos@nereida:~/src/groovy/strings$ groovy ScanSum.groovy next = 3.5 sum=3.5 next = 4.2 sum=7.7 next = 83.0 sum=90.7 90.7

Clase scanner en Java


Publicado en 2 septiembre, 2010 de emonteblack

Java tiene un metodo llamado System.in, la cual obtiene la informacion de usuario. Sin embargo, Sytem.in no es tan simple como System.out. La razon porque no es tan facil es porque System.in solo lee la informacion en bytes. Bytes no nos sirve de mucho ya que los programas usualmente trabajan con valores de otro tipo (integrales, Strings, bool, etc). Para solucionar este problema usamos la clase Scanner. La clase Scanner esta diseado para leer los bytes y convertirlo en valores primitivos (int, double, bool, etc) o en valores String. Acontinuacion se detalla el funcionamiento de esta clase: Primero tiene que crear un objeto Scanner y conectarlo con System.in Scanner teclado = new Scanner(System.in); Veamos este codigo por partes.La primera parte: Scanner teclado Este codigo declara una variable llamado teclado. El tipo de data de esta variable es Scanner. Ya que Scanner es una clase, la variable teclado es un objeto de la clase Scanner. La segunda parte: = new Scanner(System.in); Lo primero que vemos es el simbolo =, lo cual esta asignando un valor a la variable teclado. El valor es Scanner(System.in) que en palabras comunes esta diciendo que el valor de teclado es lo que System.in tenga. Osea, cuando un usuario presiona una tecla, la computadora convierte esta informacion en bytes. Estos bytes son guardados en el objeto System.in, y por ultimo son asignados a la variable teclado. Despues del simbolo = vemos la palabra clave

new lo cual crea un nuevo objeto en la memoria, el tipo de objeto que creara es Scanner(System.in), basicamente esta reservando memoria en la computadora para que se pueda guardar la informacion de System.in. A continuacion el siguiente ejemplo para dar mas claridad: int edad; Scanner teclado = new Scanner(System.in); System.out.println(Que edad tienes); edad = teclado.nextInt(); Veamos paso a paso que es lo que significa cada linea: int edad : Estamos declarando una variable int llamada edad la cual va a almacenar un numero. Scanner teclado = new Scanner(System.in); : Estamos declarando una variable Scanner, la cual va almacenar la informacion que el usuario introduce. System.out.println(Cual es tu edad); : Estamos usando el metodo println para preguntar al usuario por su edad. edad = teclado.nextInt(); : Estamos usando la variable teclado para obtener la informacion del usuario, luego convertimos los bytes en int con el metodo nextInt, y por ultimo estamos pasando el valor int a la variable edad Existen varios metodos de la clase Scanner para convertir bytes en valores que sean mas utiles. Siguiente voy a mostrar una lista de los metodos mas comunes de la clase Scanner para convertir bytes en otros valores. Metodos: nextByte nextDouble nextFloat

nextInt nextLine nextLong La mayoria de estos metodos se sobre entienden. Hay 2 que necesitan un poco mas de explicacion. El metodo nextByte no significa que va a reconvertir la informacion en bytes, sino que va a transformar la informacion en el valor byte la cual puede ser un numero del -128 al +127. El siguiente metodo que quisiera explicar es nextLine, nextLine convierte los bytes

Read File Line by line using BufferedReader


Read File Line by line using BufferedReader
In this section you will learn how to read line by line data from a file using BufferedReader. In this section, we provide you two examples: 1. Read line by only using BufferedReader 2. Read line by using FileInputStream, DataInputStream, BufferedReader. What is BufferedReader ? BufferedReader buffer character to read characters, arrays and lines. It read text from a character-input stream. You can change the buffer size or can use default size. What is DataInputStream ? From reading java data types from a input stream in a machine independent way, we incorporate DataInputStream.

Example
Read line by only using BufferedReader

import java.io.*; public class BufferedReaderDemo { public static void main(String[] args) { try { BufferedReader br = new BufferedReader( new FileReader("DevFile.txt")); String devstr; while ((devstr = br.readLine()) != null) { System.out.println(devstr); } } catch (IOException e) { } } }

Ejemplo completo con la clase Scanner


Publicado en 2 septiembre, 2010 de emonteblack

Usando La Declaracion import Para poder usar la clase Scanner tienes que llamarla. La clase Scanner no esta disponible automaticamente cuando programas con Java. Para llamarla necesitas el siguiente codigo: import java.util.Scanner; Esta declaracion le dice al compilador donde esta ubicado la libreria donde la clase Scanner esta. Ejemplo de la clase Scanner en el progama Salario: import java.util.Scanner //Importa la clase Scanner public class Salario {

public static void main(String [] args) { String nombre; int horas; double pagoPorHora, pagoTotal; Scanner teclado = new Scanner(Systemin); System.println.out(Como te llamas?); nombre = teclado.nextLine(); System.println.out(Cuantas horas trabajaste esta semana?); horas = teclado.nextInt(); System.println.out(Cuanto te pagan por hora?); pagoPorHora = teclado.nextDouble(); pagoTotal = horas * pagoPorHora; System.out.println(Hola + nombre); System.out.println(Tu sueldo es $ + pagoTotal); } }

About these ads

Das könnte Ihnen auch gefallen