The use of reference data types is different from defining variables of basic data types. The variable definition and assignment of reference data types has a relatively fixed procedure or format.
1 datatype variable name = new datatype();
Each reference data type has its function, and we can call the function of an instance of that type.
variablename.methodname();
Scanner class: It is a kind of reference data type. We can use this class to complete the user keyboard input and obtain the input data.
Steps to use Scanner :
1. Import package: import java.util.Scanner; 2. Create object instance: Scanner sc = new Scanner(System.in);
Call method:
1 int i = sc.nextInt(); used to receive the number entered from the console 2 String s = sc.next(); used to receive the string entered from the console
ScannerDemo.java code file
1 /* 2 Reference data type, introduce a class Scanner 3 java already exists, it is a class made by Sun company for us, use him 4 to define reference data type variables, which are different from basic type variables 5 int a = 1; 6 format : 7 Type variable name = new type(); 8 Example: Create a variable of Scanner class 9 Scanner sc = new Scanner(); 10 int a = 1; 11 Each reference type has its own function, how to use the function 12 Formula: 13 Variable. Function name () 14 15 Scanner class, role, let me accept keyboard input on the command line 16 Use Scanner class steps: 17 1. Import the package, specify the folder where the class is located, the keyword import 18 java folder - util folder 19 2. Formula, create Scanner type variable 20 3. Variable. Use the functions in Scanner class to complete keyboard input 21 */ 22 import java.util.Scanner; 23 public class ScannerDemo{ 24 public static void main(String[] args){ 25 // Type variable name = new type(); 26 // Create Scanner, class variable 27 Scanner sc = new Scanner(System.in); 28 //Variable.Function name() accepts keyboard input 29 / / Function: nextInt() accepts keyboard input, ensuring that the input is an integer 30 // The data accepted by the function is an integer, and the result after the function runs is an integer type 31 inti = sc.nextInt(); 32 System.out.println(i+5 ); 33 34 // Another function of the Scanner class next() accepts a string input from the keyboard 35 String s = sc.next(); 36 System.out.println(s+9 ); 37 } 38 }
operation result: