1. Java中的Scanner類
Scanner類是一個掃描器,可以通過Scanner類獲得用戶在控制臺錄入的數(shù)據(jù)。(類似python中的input函數(shù),用來獲取用戶輸入內容)
// 1. 導包
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
// 2. 創(chuàng)建對象
Scanner sc = new Scanner(System.in);
System.out.println("please input a number:");
// 3. 接收數(shù)據(jù)
int i = sc.nextInt();
System.out.println("i:" + i);
}
}

image.png
2. 流程控制結構之選擇結構
流程控制結構就是通過一些特定的語句控制代碼的執(zhí)行順序從而完成特定的功能。
流程控制結構的分類:順序結構、選擇(判斷)結構、循環(huán)結構
2.1 if語句的三種格式
第一種:
if (關系表達式) {
// 語句體
}
第二種:
if (關系表達式) {
// 語句體1
} else {
// 語句體2
}
第三種:
if (關系表達式1) {
// 語句體1
} else if (關系表達式2) {
// 語句體2
} //...
else {
// 語句體n+1
}
三種導包方式:
- 手動導包
- 點擊鼠標自動生成
- 快捷鍵:Alt+Enter(在類名后使用快捷鍵)
2.2 switch語句

image.png
// 1. 導包
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
// 2. 創(chuàng)建對象
Scanner sc = new Scanner(System.in);
System.out.println("please input a number:");
// 3. 接收數(shù)據(jù)
int week = sc.nextInt();
switch (week) {
case 1:
System.out.println("星期一");
break;
case 2:
System.out.println("星期二");
break;
case 3:
System.out.println("星期三");
break;
case 4:
System.out.println("星期四");
break;
case 5:
System.out.println("星期五");
break;
case 6:
System.out.println("星期六");
break;
case 7:
System.out.println("星期日");
break;
default:
System.out.println("我不認識這樣的日期,你是外星來的吧");
break;
}
}
}
3. 流程控制之循環(huán)結構
3.1 for循環(huán)
public class ForDemo {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("Hello World");
}
}
}
3.2 while循環(huán)
public class ForDemo {
public static void main(String[] args) {
// 初始化語句
int i = 1;
// 判斷條件語句
while (i <= 5) {
// 循環(huán)體語句
System.out.println(i);
// 控制條件語句
i++;
}
}
}
3.3 do...while循環(huán)
do...while循環(huán)的循環(huán)體語句至少執(zhí)行一遍
public class ForDemo {
public static void main(String[] args) {
int count = 1;
boolean isOK = false;
do {
System.out.println("正在進行第" + count + "次練習");
if (count >= 3) {
isOK = true;
}
count++;
} while (!isOK);
}
}
3.4 三種循環(huán)的區(qū)別

image.png
3.5 死循環(huán)

image.png
3.6 break與continue
break:用于switch語句和循環(huán)語句,在switch語句中表示結束switch代碼塊,在循環(huán)語句中表示結束循環(huán)。
continue:用于循環(huán)語句,表示結束當前循環(huán),繼續(xù)下次循環(huán)
4. Random類
import java.util.Random;
public class RandomDemo {
public static void main(String[] args) {
// 生成5個[0,10)的隨機數(shù)
Random r = new Random();
for (int i = 0; i < 5; i++) {
int num = r.nextInt(10); // 生成的隨機數(shù)范圍是[0,10)
System.out.println(num);
}
}
}