java語言語法高級部分常用API(一)學習總結如下:
一:Scanner類
1、什麼是Scanner類?
一個可以解析基本類型和字符串的簡單文本掃描器。
2、通過 Scanner 類可以獲取用戶的輸入,創建 Scanner 對象的基本語法如下:
Scanner sc = new Scanner(System.in);
備註:System.in 系統輸入指的是通過鍵盤錄入數據。
3、導包:
java.util.Scanner;
4、常用方法如下:
-
nextInt()、next()和nextLine()
- nextInt():
(nextInt()只讀取數值,剩下”\n”還沒有讀取,並將cursor放在本行中) - next():
next() 方法遇見第一個有效字符(非空格,非換行符)時,開始掃描,當遇見第一個分隔符或結束符(空格或換行符)時,結束掃描,獲取掃描到的內容,即獲得第一個掃描到的不含空格、換行符的單個字符串。 - nextLine():
nextLine()時,則可以掃描到一行內容並作爲一個字符串而被獲取到。
- nextInt():
補充一個方法:
Java中List轉換爲數組,數組轉List
List轉換爲Array可以這樣處理:
ArrayList list=new ArrayList();
String[] strings = new String[list.size()];
list.toArray(strings);
反過來,如果要將數組轉成List怎麼辦呢?如下:
String[] s = {“a”,“b”,“c”}; List list = java.util.Arrays.asList(s);
實踐代碼如下:
import java.util.Scanner;
public class ScannerMethod {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("請輸入第一個數字:");
int num = sc.nextInt();
System.out.println(num);
System.out.println("請輸入一個字符串:");
String str1 = sc.next();
System.out.println(str1);
System.out.println("請輸入一行數據:");
String str2 = sc.nextLine();
System.out.println(str2);
}
}
結果如下:
操作如下: |
import java.util.Scanner;
public class ScannerMethod {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("請輸入第一個數字:");
int num = sc.nextInt();
System.out.println(num);
System.out.println("請輸入一個字符串:");
String str1 = sc.next();
System.out.println(str1);
sc.nextLine();//在這裏在增加一行sc.nextLine();將被next()等去掉的enter結束符過濾掉。
System.out.println("請輸入一行數據:");
String str2 = sc.nextLine();
System.out.println(str2);
}
}
02
二:Random類
此類的實例用於生成僞隨機數。
Random r = new Random();
int i = r.nextInt();
查看成員方法
public int nextInt(int n) :返回一個僞隨機數,範圍在 0 (包括)和 指定值 n (不包括)之間的 int 值。
猜數字小遊戲代碼展示:
//猜字小遊戲
Random r = new Random();
int realNum = r.nextInt(10);
Scanner sc = new Scanner(System.in);
while(true){
System.out.println("答案爲:"+realNum);
System.out.println("請你猜一個數字:");
int input = sc.nextInt();
if(input<realNum){
System.out.println("你輸入的數字小啦!請重新輸入");
}
else if(input>realNum){
System.out.println("你輸入的數字大啦!請重新輸入");
}
else{
System.out.println("恭喜你猜對了!");
break;
}
}
03
三:ArrayList類
java.util.ArrayList 是大小可變的數組的實現,存儲在內的數據稱爲元素。此類提供一些方法來操作內部存儲 的元素。 ArrayList 中可不斷添加元素,其大小也自動增長。
導包語句:
import java.util.ArrayList;
java.util.ArrayList :該類需要 import導入使後使用。
<E> ,表示一種指定的數據類型,叫做泛型。 E ,取自Element(元素)的首字母。在出現 E 的地方,我們使用一種引用數據類型將其替換即可,表示我們將存儲哪種引用類型的元素。代碼如下:
ArrayList<String>,ArrayList<Student>
ArrayList<Integer> list1 = new ArrayList<>();
常用方法和遍歷
對於元素的操作,基本體現在——增、刪、查。常用的方法有: public boolean add(E e) :將指定的元素添加到此集合的尾部。
public E remove(int index) :移除此集合中指定位置上的元素。返回被刪除的元素。 public E get(int index) :返回此集合中指定位置上的元素。返回獲取的元素。
public int size() :返回此集合中的元素數。遍歷集合時,可以控制索引範圍,防止越界。 這些都是基本的方法,操作非常簡單,代碼如下:
實踐代碼如下:
import java.util.ArrayList;
import java.util.Random;
public class ArrayList1 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("趙麗穎");
System.out.println(list);
list.add("迪麗熱巴");
list.add("古力娜扎");
list.add("瑪爾拉哈");
System.out.println(list);
System.out.println(list.get(0));
// System.out.println(list.remove(3));
// System.out.println(list.get(3));
int size1 = list.size();
System.out.println(list.size());
for(int i = 0;i<list.size();i++){
System.out.println(list.get(i));
}
//遍歷集合
ArrayList<Integer> list1 = new ArrayList<>();
Random r = new Random();
for(int i = 0;i<100;i++){
list1.add(r.nextInt(10));
}
for(int i = 0 ;i<list1.size();i++){
System.out.print("-->"+list1.get(i));
if(i%25 == 0&&i!=0){
System.out.println();
}
}
//添加四個對象的list集合中並且遍歷對象數組
ArrayList<Student> list2 = new ArrayList<>();
Student one = new Student("洪七公",52);
Student two = new Student("歐陽鋒",52);
Student three = new Student("黃藥師",52);
Student four = new Student("楊過",28);
list2.add(one);
list2.add(two);
list2.add(three);
list2.add(four);
System.out.println();
for(int i = 0;i<list2.size();i++){
System.out.println("姓甚名誰:"+list2.get(i).getName()+" 年齡:"+list2.get(i).getAge());
}
//使用{}擴起集合,使用@分割每個元素。
printArrayList1(list);
ArrayList<Integer> list4 = new ArrayList();
Random r1 = new Random();
for(int i = 0;i<20;i++){
list4.add(r1.nextInt(10));
}
System.out.println(list4);
oushu(list4);
System.out.println(list4);
}
//格式如下:{趙麗穎@迪麗熱巴@古力娜扎@瑪爾拉哈}
//方法
public static void printArrayList(ArrayList<String> list){
String[] a = new String[list.size()];
list.toArray(a);
for(int i = 0;i<a.length;i++){
if(i==0){
System.out.print("{");
}
System.out.print(a[i]);
if(i!=a.length-1){
System.out.print("@");
}
}
System.out.println("}");
}
public static void printArrayList1(ArrayList<String> list){
System.out.print("{");
for(int i = 0;i<list.size();i++){
System.out.print(list.get(i));
if(i!=list.size()-1){
System.out.print("@");
}
}
System.out.print("}");
}
//用list.remove 方法遇到的問題
public static void oushu(ArrayList<Integer> list){
for(int i = list.size()-1;i>=0;i--){
if(list.get(i)%2==1){
list.remove(i);
}
}
System.out.println(list);
}
}
原因:List每remove掉一個元素以後,後面的元素都會向前移動,此時如果執行i=i+1,則剛剛移過來的元素沒有被讀取。
解決方法:
1.倒過來遍歷list
for (int i = list.size()-1; i > =0; i--) {
if (((String) list.get(i)).startsWith("abcde")) {
list.remove(i);
}
}
2.每移除一個元素以後再把i移回來
for (int i = 0; i < list.size(); i++) {
if (((String) list.get(i)).startsWith("abcde")) {
list.remove(i);
i=i-1;
}
}
3.使用iterator.remove()方法刪除
for (Iterator it = list.iterator(); it.hasNext();) {
String str = (String)it.next();
if (str.equals("chengang")){
it.remove();
}
}
04
四:String類
java.lang.String 類代表字符串。
1、特點:
(1). 字符串不變:字符串的值在創建後不能被更改。(具體詳見代碼)
public class StringMethod {
public static void main(String[] args) {
String s1 = "abc";
s1+="d";
System.out.println(s1);
// 內存中有"abc","abcd"兩個對象,s1從指向"abc",改變指向,指向了"abcd"。
}
}
結果如下:
(2). 因爲String對象是不可變的,所以它們可以被共享。
String s1 = "abc";
String s2 = "abc";
// 內存中只有一個"abc"對象被創建,同時被s1和s2共享。
(3). “abc” 等效於 char[] data={ ‘a’ , ‘b’ , ‘c’ } 。
//例如
String str = "abc";
// 相當於
char[] data = {'a','b','c'};
String str = new String(data);
// String底層是靠字符數組實現的。
2、方法使用:
(1)java.lang.String :此類不需要導入包。
(2)查看構造方法:
public String() :初始化新創建的 String對象,以使其表示空字符序列。
public String(char[] value) :通過當前參數中的字符數組來構造新的String。
public String(byte[] bytes) :通過使用平臺的默認字符集解碼當前參數中的字節數組來構造新的 String。 構造舉例,代碼如下:
public class StringMethod {
public static void main(String[] args) {
//無參構造
String str = new String();
//通過字符數組構造
char[] data = {'a','b','c'};
String str2 = new String(data);
//通過字節數組構造
byte[] bytes = {97,98,99};
String str3 = new String(bytes);
System.out.println(str2);
System.out.println(str3);
}
}
(3)獲取功能的方法:
public int length () :返回此字符串的長度。 public String concat (String str) :將指定的字符串連接到該字符串的末尾。 public char charAt (int index) :返回指定索引處的 char值。 public int indexOf (String str) :返回指定子字符串第一次出現在該字符串內的索引。
public String substring (int beginIndex) :返回一個子字符串,從beginIndex開始截取字符串到字符 串結尾。
public String substring (int beginIndex, int endIndex) :返回一個子字符串,從beginIndex到 endIndex截取字符串。含beginIndex,不含endIndex。
(4)轉換功能的方法:
public char[] toCharArray () :將此字符串轉換爲新的字符數組。
public byte[] getBytes () :使用平臺的默認字符集將該 String編碼轉換爲新的字節數組。
public String replace (CharSequence target,CharSequence replacement) :將與target匹配的字符串使 用replacement字符串替換。
(5)分割功能的方法:
public String[] split(String regex) :將此字符串按照給定的regex(規則)拆分爲字符串數組。
小練:鍵盤錄入一個字符串數據,統計字符串中大小寫字母及數字字符個數。
代碼如下:
import java.util.Scanner;
public class StringMethod {
public static void main(String[] args) {
//鍵盤錄入一個字符串數據,統計字符串中大小寫字母及數字字符個數
System.out.println("請從鍵盤輸入一個字符串數據:");
Scanner sc = new Scanner(System.in);
String str = sc.next();
int bigCount = 0;//定義瞭如下三個計數器分別統計大寫字母與小寫字母和數字的個數。
int smallCount = 0;
int numberCount = 0;
for(int i = 0; i<str.length();i++){
char ch = str.charAt(i);
if(ch>='a'&&ch<='z'){
smallCount++;
}
else if(ch>='A'&&ch<='Z'){
bigCount++;
}
else if(ch>='0'&&ch<='9'){
numberCount++;
}
else{
System.out.println("該字符非法:"+ch);
}
}
System.out.println("小寫字母的個數爲:"+smallCount);
System.out.println("大寫字母的個數爲:"+bigCount);
System.out.println("數字的個數爲:"+numberCount);
}
}
3、一些底層原理:
05
五:static關鍵字
1、 概述
關於 static 關鍵字的使用,它可以用來修飾的成員變量和成員方法,被修飾的成員是屬於類的,而不是單單是屬 於某個對象的。也就是說,既然屬於類,就可以不靠創建對象來調用了。
2、類變量
當 static 修飾成員變量時,該變量稱爲類變量。該類的每個對象都共享同一個類變量的值。任何對象都可以更改該類變量的值,但也可以在不創建該類的對象的情況下對類變量進行操作。(多個對象共享同一份數據)
類變量:使用 static關鍵字修飾的成員變量。
格式:static 數據類型 變量名;
3、應用場景
比如說,基礎班新班開班,學員報到。現在想爲每一位新來報到的同學編學號(sid),從第一名同學開始,sid爲 1,以此類推。學號必須是唯一的,連續的,並且與班級的人數相符,這樣以便知道,要分配給下一名新同學的學 號是多少。這樣我們就需要一個變量,與單獨的每一個學生對象無關,而是與整個班級同學數量有關。
所以,我們可以這樣定義一個靜態變量num,代碼如下:
public class Student {
private String name;
private int age;
private int sid;//我們定義一個sid來記錄每一個學生的學號,並讓它實現自增長
//即每當創建一個對象的時候,讓其加一。
//因爲sid是每一個人都有的且各不相同,所以我們不能將此變量設置爲共享變量。
//我們設置另一個變量爲共享變量達到控制sid實現自增長。
public static int num = 0;//static修飾的共享變量!
public Student() {
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public Student(String name, int age) {
this.name = name;
this.age = age;
this.sid =++num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class StudentDemo {
public static void main(String[] args) {
Student stu1 = new Student("楊過",19);
Student stu2 = new Student("郭靖",38);
Student stu3 = new Student("黃蓉",35);
Student stu4 = new Student("東方不敗",25);
Student stu5 = new Student("任我行",50);
System.out.println("報上大名:大家好,我是"+stu1.getName()+" 年齡:我今年"+ stu1.getAge()+"歲了!"+"我的學號是:"+stu1.getSid());
System.out.println("報上大名:大家好,我是"+stu2.getName()+" 年齡:我今年"+ stu2.getAge()+"歲了!"+"我的學號是:"+stu2.getSid());
System.out.println("報上大名:大家好,我是"+stu3.getName()+" 年齡:我今年"+ stu3.getAge()+"歲了!"+"我的學號是:"+stu3.getSid());
System.out.println("報上大名:大家好,我是"+stu4.getName()+" 年齡:我今年"+ stu4.getAge()+"歲了!"+"我的學號是:"+stu4.getSid());
System.out.println("報上大名:大家好,我是"+stu5.getName()+" 年齡:我今年"+ stu5.getAge()+"歲了!"+"我的學號是:"+stu5.getSid());
}
}
結果如下:
4、靜態方法
當 static 修飾成員方法時,該方法稱爲類方法 。靜態方法在聲明中有 static ,建議使用類名來調用,而不需要 創建類的對象。調用方式非常簡單。
類方法:使用 static關鍵字修飾的成員方法,習慣稱爲靜態方法。
定義格式:
public static void showNum(){
System.out.println("一共有多少個學生:"+num);
}
靜態方法調用的注意事項: 靜態方法可以直接訪問類變量和靜態方法。 靜態方法不能直接訪問普通成員變量或成員方法。反之,成員方法可以直接訪問類變量或靜態方法。 靜態方法中,不能使用this關鍵字。
Do you know?:靜態方法只能訪問靜態成員。
調用格式 :
被static修飾的成員可以並且建議通過類名直接訪問。雖然也可以通過對象名訪問靜態成員,原因即多個對象均屬 於一個類,共享使用同一個靜態成員,但是不建議,會出現警告信息。
格式:
// 訪問類變量 類名.類變量名;
// 調用靜態方法 類名.靜態方法名(參數);
5、靜態代碼塊:
靜態代碼塊:定義在成員位置,使用static修飾的代碼塊{ }。 位置:類中方法外。 執行:隨着類的加載而執行且執行一次,優先於main方法和構造方法的執行。
格式:
//靜態代碼塊格式:
public class ClassName(){
static{
//執行語句
}
}
public class Test{
public static int number;
public static ArrayList<String> list;
static{
//給類變量進行賦值
number = 66;
list = new ArrayList<String>();
//添加元素到集合中
list.add("風清揚");
list.add("東方不敗");
System.out.println(list);
}
}
錦囊妙計:
static 關鍵字,可以修飾變量、方法和代碼塊。在使用的過程中,其主要目的還是想在不創建對象的情況 下,去調用方法。下面將介紹兩個工具類,來體現static 方法的便利。
06
六:Math工具類
1、 概述
java.lang.Math 類包含用於執行基本數學運算的方法,如初等指數、對數、平方根和三角函數。類似這樣的工具 類,其所有方法均爲靜態方法,並且不會創建對象,調用起來非常簡單。
2、 基本運算的方法
(1)public static double abs(double a) :返回 double 值的絕對值。
double d1 = Math.abs(‐5); //d1的值爲5
double d2 = Math.abs(5); //d2的值爲5
(2)public static double ceil(double a) :返回大於等於參數的小的整數。
double d1 = Math.ceil(3.3); //d1的值爲 4.0
double d2 = Math.ceil(‐3.3); //d2的值爲 ‐3.0
double d3 = Math.ceil(5.1); //d3的值爲 6.0
(3)public static double floor(double a) :返回小於等於參數大的整數。
double d1 = Math.floor(3.3); //d1的值爲3.0
double d2 = Math.floor(‐3.3); //d2的值爲‐4.0
double d3 = Math.floor(5.1); //d3的值爲 5.0
(4)public static long round(double a) :返回接近參數的 long。(相當於四捨五入方法)
long d1 = Math.round(5.5); //d1的值爲6.0
long d2 = Math.round(5.4); //d2的值爲5.0
07
七:ArrayList工具類
1、概述
java.util.Arrays 此類包含用來操作數組的各種方法,比如排序和搜索等。其所有方法均爲靜態方法,調用起來 非常簡單。
2、 操作數組的方法
(1)public static String toString(int[] a) :返回指定數組內容的字符串表示形式。
public class StudentDemo {
public static void main(String[] args) {
int[] nums = {5,56,45,487,666,13};
//將數組內容轉換爲字符串
String str = Arrays.toString(nums);
System.out.println(str);//[5, 56, 45, 487, 666, 13]此爲輸出內容,帶格式輸出。
}
}
(2)public static void sort(int[] a) :對指定的 int 型數組按數字升序進行排序。
public class StudentDemo {
public static void main(String[] args) {
int[] data = {2,8,65,4,3,45};
Arrays.sort(data);
System.out.println(Arrays.toString(data));//排序後[2, 3, 4, 8, 45, 65]
}
}
08
八:匿名對象
創建對象時,只有創建對象的語句,卻沒有把對象地址值賦值給某個變量。雖然是創建對象的簡化寫法,但是應用 場景非常有限。
1、匿名對象 :沒有變量名的對象。
2、格式:
new 類名(參數列表);
new Scanner(System.in);
3、應用場景:
(1). 創建匿名對象直接調用方法,沒有變量名。
new Scanner(System.in).nextInt();
(2).一旦調用兩次方法,就是創建了兩個對象,造成浪費,請看如下代碼。
new Scanner(System.in).nextInt();
new Scanner(System.in).nextInt();
小貼士:一個匿名對象,只能使用一次。(因爲new一下,就是另外一個對象了)
(3). 匿名對象可以作爲方法的參數和返回值
System.out.println("Scanner的使用方法和匿名對象的使用方法如下:");
System.out.println("普通使用方式:");
Scanner sc = new Scanner(System.in);
int s1 = sc.nextInt();
String s2 = sc.next();
System.out.println("輸入的數字是:"+s1);
System.out.println("輸入的字符是:"+s2);
System.out.println("匿名對象使用方式:");
int num = new Scanner(System.in).nextInt();
System.out.println("輸入的數字是:"+num);
System.out.println("普通使用方式傳參:");
Scanner sc1 = new Scanner(System.in);
methodParam(sc1);
System.out.println("匿名對象方式傳參:");
methodParam(new Scanner(System.in));
System.out.println("匿名對象作爲返回值:");
Scanner sc2 = methodReturn();
int num2 = sc2.nextInt();
System.out.println("匿名對象作爲返回值:"+num2);
//下面是定義的兩個方法
public static void methodParam(Scanner sc){
int num = sc.nextInt();
System.out.println("輸入的字符是:"+num);
}
public static Scanner methodReturn(){
return new Scanner(System.in);
}