miércoles, 2 de julio de 2014

MODULO 11: Consola I/O

Salida con formato

public class SFO {
    public static void main(String[] args) {
        double nd = 123.4567;
        System.out.printf("%08.2f %n", nd);
        //Son 8 por todos los caracteres incluyendo el punto
        // 2 significa que son dos digitales a la derecha.
        //f -> flotantes, double. %g -> Notacion cientifica
        //%d %o %x Entero, decimal, octal, o hexadecimal.
        //%n nueva linea al igual que \n
        //%s String
    }
}

Preguntas en evaluación lo siguientes métodos
 StringreadLine()
          Reads a single line of text from the console.
LOS MÉTODOS ESTÁN SOBRECARGADOS
 char[]readPassword()
          Reads a password or passphrase from the console with echoing disabled

OBSERVACIÓN: RedLine en cualquiera de sus formas regresa un STRING y readPassword  regresa un arreglo de caracteres char[].

Ejemplo de preguntas:
QUESTION NO: 1

Given:
5. import java.io.*;
6. public class Talk {
7. public static void main(String[] args) {
8. Console c = new Console();
9. String pw;
10. System.out.print("password: ");
11. pw = c.readLine();
12. System.out.println("got " + pw);
13. }
14. }

If the user types the password aiko when prompted, what is the result?

A. password:
got
B. password:

got aiko
C. password: aiko
got aiko
D. An exception is thrown at runtime.
E. Compilation fails due to an error on line 8.

Answer: ?

.
.
.
.

Answer E

Console no se puede instanciar porque su constructor es privado, para instanciarlo se utiliza:
Console c = System.Console();

QUESTION NO: 2

Given that c is a reference to a valid java.io.Console object, which two code fragments read a line of text from the console? (Choose two.)

A. String s = c.readLine();
B. char[] c = c.readLine();
C. String s = c.readConsole();
D. char[] c = c.readConsole();
E. String s = c.readLine("%s", "name ");
F. char[] c = c.readLine("%s", "name ");

Answer: ?

.
.
.

Answer: A, E

QUESTION NO: 3

Given that c is a reference to a valid java.io.Console object, and:
11. String pw = c.readPassword("%s", "pw: ");
12. System.out.println("got " + pw);
13. String name = c.readLine("%s", "name: ");
14. System.out.println(" got ", name);
If the user types fido when prompted for a password, and then responds bob when prompted for a name, what is the result?

A. pw: got fido name: bob got bob
B. pw: fido got fido name: bob got bob
C. pw: got fido name: bob got bob
D. pw: fido got fido name: bob got bob
E. Compilation fails.
F. An exception is thrown at runtime.

Answer: ?
.
.
.
.
.

Answer: E
Error en linea 11 porque readPassword regresa un arreglo de caracteres


-- Parentesis -----------------------------------------------------------------------------------------------
boolean assert = true; //En la versión 6, 5 y 4 de java es palabra reservada pero en las versiones anteriores es una palabra normal.
------------------------------------------------------------------------------------------------------------

Clase Scanner

public class EjCS {
 
    public static void main(String[] args) {
         Scanner sc = new Scanner(System.in);
//         int i = sc.nextInt(); //Solo recibe enteros, si es otra cosa marca error
//         System.out.println("Leí: "+i);
         String s="";
     
         while(sc.hasNext()){
           
             if(sc.nextLine().equals("x") ){
             break;
            }
           
             s += sc.nextLine();
             System.out.println("Leí: "+s);
         }
       
    }

}

Entrada y Salida de archivos
Para esto podemos leer y escribir de un archivo y una forma de hacerlo es así:

------------------------------------------------------------------------------------------------------------
public class CFD {
    public static void main(String[] args) {
        //crear objeto File para directorio
        try {
            File md = new File("MiArchivo");
            File f = new File(md, "file_1.txt");
            md.mkdir();
            try {
                f.createNewFile();
             
                //Leer desde el teclado y escribir en el archivo creado.
                InputStreamReader isr = new InputStreamReader(System.in);
                //crear buffer de lectura
                BufferedReader br = new BufferedReader(isr);
             
                //Escribir en el archivo
                PrintWriter pw = new PrintWriter( new FileWriter(f, true) ); //El true es para que agregue
                System.out.println("Ingresa texto!");
             
                String s="";
                //Leer lineas
                while ( (s=br.readLine()) != null && !s.equals("x")) {
                    pw.println(s);
                }
                br.close();
                pw.close();
             
                //Fase 2
                //Leer el texto del archivo creado y mostrarlo por consola
                BufferedReader br2 = new BufferedReader(new FileReader(f));
                String s2 ="";
                while ( (s2=br2.readLine()) != null ) {
                    System.out.println("Lectura--  "+s2);
                }
                br2.close();
             
            } catch (IOException ioe) {
                System.err.println("No se puede crear un archivo");
            }

        } catch (Exception e) {
        }
    }
}

-----------------------------------------------------------------------------------------------------------








No hay comentarios:

Publicar un comentario