How to call a class in Java?
To invoke a class, you need to follow these steps:
- Importing classes: At the beginning of Java code, use the import statement to import the class that needs to be called. For example, to call the Scanner class, you can use import java.util.Scanner;.
- Creating objects: Use the “new” keyword to create an instance of a class. For example, to create a Scanner object, you can use “Scanner scanner = new Scanner(System.in);”.
- To call a class method: use the object name followed by a dot to call the class method. For example, to use the nextInt() method of a Scanner object to read an integer, you can use int number = scanner.nextInt();.
Here is a complete example code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// 创建Scanner对象
Scanner scanner = new Scanner(System.in);
// 调用nextInt()方法读取一个整数
System.out.println("请输入一个整数:");
int number = scanner.nextInt();
System.out.println("你输入的整数是:" + number);
// 调用nextLine()方法读取一行字符串
System.out.println("请输入一行字符串:");
scanner.nextLine(); // 读取nextInt()方法后的换行符
String line = scanner.nextLine();
System.out.println("你输入的字符串是:" + line);
// 关闭Scanner对象
scanner.close();
}
}
This sample code utilizes the Scanner class to read integers and strings inputted by the user, and then prints them.