Up to now, we have introduced a lot of object-oriented concepts and implementations.
Today, we will introduce a ready-made tool that is very convenient to use in Java (or other programs)—packages.
There are two types of packages:
The library is further divided into → single categories and entire packages
When we want to use a package, we must use the keyword import
at the beginning of the program to import the members in the library.
import java.util.Scanner; //Import a class(Scanner)
import java.util.*; //Import a package(java.util)
Scanner是java.util套件中的一個類別,import套件同時,也能使用裡面之類別
We call the Scanner class in the java.util package in the library to read the contents from the user input.
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner new_obj = new Scanner(System.in);
int[] grade={0,0,0};
int count = 1;
while(count <= 3){
System.out.println("Student " + count + " grade: ");
grade[ count-1 ] = new_obj.nextInt();
}
}
}
To import the entire package, we must change to → java.util .*
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner new_obj = new Scanner(System.in);
int[] grade={0,0,0};
int count = 1;
while(count <= 3){
System.out.println("Student " + count + " grade: ");
grade[ count-1 ] = new_obj.nextInt();
}
}
}
There are two things to note about self-declared packages:
package package_name;
class package_class{
/***************
**description**
****************/
}
package greeting;
class greetingClass{
public static void main(String[] args) {
System.out.println("Hello World!!!");
}
First set the file address.
Category tool in the editing suite
! Note this step!
Here we specify the location where it will be stored. The keyword -d
is used together with the address (C:, D:)
If you want to put the package in the same file location, just add . after -d.
import