编程知识 cdmana.com

Usage of Java scanner

{tabs-pane label=" About nextInt()、next() and nextLine() Usage of "} nextInt():nextInt() Read only values , be left over "n" Not yet read , And will Scanner Class read depends on cursor Put it after the value ,"n" front , So if you use nextInt() After reading , Reuse nextLine() Read , Read a newline character . next():next() Read only data before spaces , also cursor Point to the bank next() Method encounters the first valid character ( Non blank space , Non newline character ) when , Start scanning , When you meet the first separator or Terminator ( Space or line break ) when , End scan , Get the scanned content , That is, get the first scanned without spaces 、 A single string of newline characters . Method ends when it reads a blank character nextLine(): You can scan a line of content and get it as a string , End with “r” End of carriage return ;

If you use next()、nextDouble() 、 nextFloat()、nextInt() After reading , In fact, there is another enter that has not been read out , If this is followed by nextLine() Read the enter . meet nextLine() if Scanner There is really nothing to read in , Will wait for you to enter . {/tabs-pane} {tabs-pane label="hasNext()"} hasNextInt() Used to determine whether the next string entered by the keyboard is Int type , return boolean, If the input is Int Type return true, Otherwise return to false, General users handle exceptions with input mismatches

hasNextInt() It's a bit like a caching mechanism , When calling hasNextInt() when , Then a value will be stored in its space , Calling again does not overwrite or increase , Instead, keep the original value . When calling next() or nextInt() The value of the space is given to next or nextInt, At the same time, empty the value in its space , Thus, a new value can be received again .

Scanner scan = new Scanner(System.in);
        System.out.println(" Please enter an integer ");
        // Two consecutive calls hasNextInt()
        boolean flag1 = scan.hasNextInt();
        // use String Type variable str receive 
        String str = scan.next();
        System.out.println(" Please enter an integer ");
        boolean flag2 = scan.hasNextInt();

{/tabs-pane}

This article altogether 398 Number of words , Average reading time ≈ 1 minute

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[await]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/09/20210909125824197o.html

Scroll to Top