Home >Java >javaTutorial >Commonly used classes in java——Scanner

Commonly used classes in java——Scanner

王林
王林forward
2019-11-28 15:02:073037browse

Commonly used classes in java——Scanner

What is the Scanner class

A simple text scanner that can parse basic types and strings. For example, the following code enables the user to read a number from System.in:

Scanner sc = new Scanner(System.in); 
int i = sc.nextInt();

Note: System.in system input refers to entering data through the keyboard.

Reference type usage steps

Guide package

Use the import keyword to import the package, import the package before all the code of the class, and introduce the type to be used. All classes under the java.lang package do not need to be imported.

Format:

import 包名.类名;

Example:

java.util.Scanner;

Learning video recommendation: java course

Create objects

Use the constructor of this class to create an object of this class. Format:

数据类型 变量名 = new 数据类型(参数列表);

Example:

Scanner sc = new Scanner(System.in);

Call method

Call the member method of this class to complete the specified function. Format:

变量名.方法名();

Example:

int i = sc.nextInt(); // 接收一个键盘录入的整数

Scanner usage steps

##View class

java.util.Scanner: This class needs to be imported before use.

View construction method

public Scanner(InputStream source)Constructs a new Scanner that generates values ​​scanned from the specified input stream of.

public int nextInt()Scan the next mark of the input information into an int value

Use the Scanner class to complete the operation of receiving keyboard input data. The code is as follows:

Commonly used classes in java——Scanner

Exercise

Summing

Keyboard input two data and sum , the code is as follows:

import java.util.Scanner; 

public class Test01Scanner {
	public static void main(String[] args) {
		// 创建对象
		Scanner sc = new Scanner(System.in);
		// 接收数据
		System.out.println("请输入第一个数据:");
		int a = sc.nextInt(); 
		System.out.println("请输入第二个数据:"); 
		int b = sc.nextInt();
		// 对数据进行求和
		int sum = a + b;
		System.out.println("sum:" + sum);
	}
}

Get the maximum value

Enter three data on the keyboard and get the maximum value, the code is as follows:

Commonly used classes in java——Scanner

More related article tutorial recommendations:

java quick start

The above is the detailed content of Commonly used classes in java——Scanner. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete