Java uses the scanner class to get user input

Source: Internet
Author: User

When writing a program in Java, some data require user input, this time need to call Java provides scanner class, this class in the package java.util, such as to find a rectangular area, a simple look at the usage:

1 ImportJava.util.Scanner;2  Public classJavashuru {3     //Java gets user input, using the scanner class, in the Java.util package4      Public Static voidMain (string[] args) {5         //Create a Scanner object6Scanner input=NewScanner (system.in);7         DoubleA,b,s;//definition of long, wide, area8System.out.print ("Please enter the length of the rectangle:");9         //get input, and save to variableTenA=input.nextdouble (); OneSystem.out.print ("Please enter the width of the rectangle:"); Ab=input.nextdouble (); -s=a*b; -System.out.println ("The area of the rectangle is:" +S); theInput.close ();//Close Input -     } -}

This allows you to receive input from the user, note that the method of the input instance in this example nextdouble () is to get the floating-point value, and if you can get the string with next (), the integer can be used Nextint ()

The last sentence input.close (); Is to close the input, it is recommended to add this sentence, if you do not add eclipse will prompt: Resource leak: ' Input ' is never closed means a resource leak: the input is not closed, So when it's closed, the program runs and ends normally.

Java uses the scanner class to get user input

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.