How to use scanner in Java

Source: Internet
Author: User

Scanner is a new class that SDK1.5 adds, but uses this class to create an object.
Scanner reader=new Scanner (system.in);
The reader object then calls the following methods (functions) to read the various data types that the user entered at the command line:Next. Byte (), nextdouble (), Nextfloat,nextint (), Nextlin (), Nextlong (), Nextshot ()
The above method will cause blocking when running, waiting for the user to enter the data return confirmation at the command line. For example, the value of 12.34,hasnextfloat () in the keyboard input is true, while the value of Hasnextint () is false. Nextline () waits for the user to enter a line of text and enter, which gets a string type of data.
Here is an example:


Import java.util.*;
public class example{
public static void Main (String args[]) {
System.out.println ("Please enter a number of numbers, each input a number with a return confirmation");
SYSTEM.OUT.PRINTLN ("Last input a non-numeric end input operation");
Scanner reader=new Scanner (system.in);
Double sum=0;
int m=0;
while (Reader.hasnextdouble ()) {
Double x=reader.nextdouble ();
m=m+1;
Sum=sum+x;
}
System.out.printf ("%d number of%f/n", m,sum);
System.out.printf ("The average of%d numbers is%f/n", m,sum/m);
}
}

How to use scanner in Java

Related Article

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.