Java's scanner

Source: Internet
Author: User

Reference Http://how2j.cn/k/operator/operator-scanner/658.html#nowhere

Need to input data from the console, so you need to use the scanner class

Reading integers using scanner
import Java.util.Scanner; Public classHelloWorld { Public Static voidMain (string[] args) {Scanner s=NewScanner (System.inch); intA =S.nextint (); System. out. println ("First integer:"+a); intb =S.nextint (); System. out. println ("a second integer:"+b); }}

Execute the program

Using scanner to read floating-point numbers
import Java.util.Scanner;    Public class HelloWorld {    publicstaticvoid  main (string[] args) {        new Scanner (System.  in);         float a = s.nextfloat ();        System. out. println (" read the value of the floating-point number is:"+a);}     }

Execute the program

Reading a string using scanner
import Java.util.Scanner;    Public class HelloWorld {    publicstaticvoid  main (string[] args) {        new Scanner (System.  in);         = s.nextline ();        System. out. println (" the string read is:"+a);}    }
After the integer is read, the string is then read

Note that if you read the integer through Nextint () and then read the string, the return line is read: "\ r \ n" because Nextint only reads the digital information, but does not read the carriage return line "\ r \ n".

Therefore, if you need to read the integer in the business, then read the string, then you should execute two times nextline (), the first time is to take a carriage return line, the second time is to read the real string

import Java.util.Scanner;  Public classHelloWorld { Public Static voidMain (string[] args) {Scanner s=NewScanner (System.inch); inti =S.nextint (); System. out. println ("The integer read is"+i); String RN=S.nextline (); String a=S.nextline (); System. out. println ("the string to read is:"+a); }}

Java's scanner

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.