Scanner is a tool in Java that reads data from input sources. To use a Scanner, perform the following steps: Create a Scanner object: Use the new Scanner statement to specify the input source. Reading data: Use the hasNext method to check if the next element exists, then use the appropriate next method to read the data element. Close Scanner: Release the resources associated with the Scanner object. Scanner provides a variety of methods to handle various data types, including integers, strings, and floating point numbers. The sample code demonstrates how to read an integer from the keyboard. Always remember to close the Scanner object.
Usage of Scanner in Java
What is Scanner?
Scanner is a tool in Java for reading data from an input source such as keyboard, file, or string. It provides a simple and convenient way to read various data types such as integers, strings, and floating point numbers element-by-element.
Using Scanner
To use Scanner, perform the following steps:
Create a Scanner object: Use the new Scanner
statement to specify the input source. For example:
<code class="java">Scanner scanner = new Scanner(System.in);</code>
Reading data: Use the hasNext
method to check if the next element exists, then use the appropriate next
Methods (such as nextInt
, nextLine
) read data elements. For example:
<code class="java">while (scanner.hasNext()) { String line = scanner.nextLine(); // 对 line 进行处理 }</code>
Close Scanner: Use the close
method to release the resources associated with the Scanner object. For example:
<code class="java">scanner.close();</code>
Available methods
Scanner provides the following methods to handle various data types:
nextBoolean
nextByte
nextDouble
The following example shows how to use Scanner to read integers from the keyboard:
<code class="java">import java.util.Scanner; public class ScannerDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); int number = scanner.nextInt(); System.out.println("Entered integer: " + number); scanner.close(); } }</code>
For floating point numbers, you can use
For strings, you can use
Always remember to close the Scanner object to release resources. The above is the detailed content of How to use Scanner in java. For more information, please follow other related articles on the PHP Chinese website!