1. Chào mừng Khách đã đến với diễn đàn java, nơi hội tụ tất cả những kỹ năng trong lập trình, chia sẻ những kinh nghiệm, bài viết, quý báu. Các bạn chỉ post bài về lập trình trong forum này. Xin Cảm Ơn!
    Dismiss Notice
  2. Trung Tâm Java - Chuyên sâu lĩnh vực đào tạo lập trình viên Java kinh nghiệm thực tế trong công việc. tìm hiểu thêm tại http://trungtamjava.com/
    Dismiss Notice

Scanner? How does it work?

Thảo luận trong 'Java Core' bắt đầu bởi Joe, 19/8/17.

  1. Joe

    Joe New Member

    Hi

    Time to be back to DiendanJava. The first thing a JAVA newbie learns is the use of Scanner. It's easy-to-use, it's convenient and it looks quite good. And that's the biggest trouble for the programming life of a newbie. What does Scanner offers ? The Scanner API gives the newbies a variety of methods that SHIELD them from understanding and learning. Instead of learning as developers they learn to run Scanner like the bots without thinking about their doing. And that's very pitiful, very sad. Maybe some Java-Instructors (or tutorials for beginner) who teach the newbies to use Scanner without previously giving them some basics (such as Stream IO and the streamed data) are as blind or as "illiterate" as the learning newbies.

    The Scanner methods are very luring...nextInt(), nexLine(), nextBtye(), nextFloat(), ...But do they know that the Scanner Implementation (see src.zip in your JAVA JDK-home) takes the development work which is very ample and in many cases superfluous? The following example inveigles the readers to work with Scanner because it's concise and looks quite good:
    PHP:
    import java.util.Scanner// <<--include this class
    public class Person_1 {
         public static 
    void main(String[] args) {
             
    Scanner input = new Scanner(System.in);
             
    System.out.print("Nhap ten: ");
             
    String name input.nextLine();                 // <---nextLine()
             
    System.out.print("Nhap tuoi: ");
           
    //int age = input.nextInt();                      // <---MAY cause troubles
             
    int age Integer.parseInt(input.nextLine());   // <---safe way
             
    System.out.print("Nhap dia chi: ");
             
    String address input.nextLine();              // <---the possible trouble     
             
    System.out.println(name " -- " temp " -- " address);
         }
    }
    Explanation:
    [​IMG]
    Let assume that you master the basics and implement the same codes as following
    PHP:
    public class Person_2  {
         public static 
    void main(String[] argsthrows Exception {
             
    int nl System.lineSeparator().length(); // NL length
             
    byte[] line = new byte[80];               // 80 character/screen-line
             
    System.out.print("Nhap ten: ");
             
    int n System.in.read(line);
             
    // n-nl: ignore the Enter character
             
    String name = new String(line0n-nl);   
             
    System.out.print("Nhap tuoi: ");
             
    System.in.read(line);
             
    int age Integer.parseInt(new String(line0n-nl));
             
    System.out.print("Nhap dia chi: ");
             
    System.in.read(line);
             
    String address = new String(line0n-nl);         
             
    System.out.println(name " -- " age " -- " address);
         }
    }
    Person_2 may look complicated, but in reality is simpler than Person_1 (see the nextLine() method). And it's clear that Person_2 has the better performance than Person_1.

    Conclusion: A creative developer uses only the standard APIs when the APIs are FULLY used. Otherwise it's much better to implement only that what (s)he really needs. It saves her/him headaches. To do that I show you, for example, how to implement your own API that replaces Scanner(System.in).
    PHP:
    /**
    This is a replacement, of Scanner(System.in). Copy the source and package in your own environment
    <p>
    Joe T. Nartca (c)
    */
    public class Console {
        
    //
        
    private Console() {
            
    buf = new byte[4096]; // 4KB
        
    }
        private 
    byte[] bufbb;
        private 
    int nl System.lineSeparator().length();
        private 
    String getLine() throws Exception {
            
    int n System.in.read(buf);
            return (new 
    String(buf,0,n-nl)).trim();
        }
        private 
    byte[] getInput() throws Exception {
            
    int n System.in.read(buf);
            return (new 
    String(buf,0,n-nl)).trim().getBytes();
        }
        
    /**
         instantiation via getConsole()
         */
        
    public static Console getConsole() {
            return new 
    Console();
        }
        
    /**
        onConsole(String msg) print the message on Console. NL (\n) must be included
        in msg if new line is desired
        */
        
    public void onConsole(String msg) {
            
    System.out.print(msg);
        }
        
    /**
        onNextLine(String msg) print the message on Console and set cursor on next line.
        */
        
    public void onNextLine(String msg) {
            
    System.out.println(msg);
        }
        
    /**
        getByte() returns the 1st byte which is not a space (0x20)
        */
        
    public byte getByte() throws Exception {
            return 
    getInput()[0];
        }
        
    /**
        getShort() returns a short
        */
        
    public short getShort() throws Exception {
            
    bb getInput();
            
    short result 0;
            for (
    int i bb.length-11>= 0; --i) {
                if (
    == && bb[i] == '-') return (short) -result;
                if (
    bb[i] > '9' || bb[i] < '0') throw new Exception(new String(bb)+" is not a number");
                
    result += (bb[i]&0x0F)*f;
                
    *= 10;
            }
            return 
    result;
        }
        
    /**
        getInt() returns an integer
        */
        
    public int getInt() throws Exception {
            
    bb getInput();
            
    int result 0;
            for (
    int i bb.length-11>= 0; --i) {
                if (
    == && bb[i] == '-') return -result;
                if (
    bb[i] > '9' || bb[i] < '0') throw new Exception(new String(bb)+" is not a number");
                
    result += (bb[i]&0x0F)*f;
                
    *= 10;
            }
            return 
    result;
        }
        
    /**
        getLong() returns a long
        */
        
    public long getLong() throws Exception {
            
    bb getInput();
            
    long result 0;
            for (
    int i bb.length-11>= 0; --i) {
                if (
    == && bb[i] == '-') return -result;
                if (
    bb[i] > '9' || bb[i] < '0') throw new Exception(new String(bb)+" is not a number");
                
    result += (bb[i]&0x0F)*f;
                
    *= 10;
            }
            return 
    result;
        }
        
    /**
        getFloat() returns a float
        */
        
    public float getFloat() throws Exception {
            return 
    Float.parseFloat(getLine());
        }
        
    /**
        getDouble() returns a double
        */
        
    public double getDouble() throws Exception {
            return 
    Double.parseDouble(getLine());
        }
        
    /**
        getString() returns a String
        */
        
    public String getString() throws Exception {
            return 
    getLine();
        }
        
    /**
        getByteArray() returns a byte array
        */
        
    public byte[] getByteArray() throws Exception {
            return 
    getInput();
        }
        
    /**
        getCharArray() returns a Char array
        */
        
    public char[] getCharArray() throws Exception {
            return 
    getLine().toCharArray();
        }
    }
    and the application is simple
    PHP:
    public class TestConsole {
       public static 
    void main(String... athrows Exception {
           
    Console c Console.getConsole();
           
    c.onConsole("Enter a byte:");
           
    System.out.printf(">>>%02X\n",c.getByte());
           
    c.onConsole("Enter a long:");
           
    System.out.printf(">>>%d\n",c.getLong());
           
    c.onConsole("Enter a double:");
           
    System.out.printf(">>>%f\n",c.getDouble());
           
    c.onConsole("Enter a String:");
           
    System.out.printf(">>>%s\n",c.getString());
           
    c.onConsole("Enter a String:");
           
    char[] ch c.getCharArray();
           
    System.out.println(">>>In char array:");
           for (
    int i 0ch.length;++iSystem.out.print(ch[i]);
           
    System.out.println();
           
    c.onNextLine("Your Name:");
           
    System.out.println(c.getString());
       }
    }
    [​IMG]
     

Chia sẻ trang này