目錄
前言
順序結構
分支結構
if 陳述句
懸垂 else
switch 陳述句
回圈結構
輸入輸出方式
輸出到控制臺
從鍵盤輸入
猜數字游戲
前言
本章主要講解:
- Java中程式的邏輯控制陳述句
- Java中的輸入輸出方式
順序結構
按照代碼書寫的順序一行一行執行
分支結構
if 陳述句
- 基本語法形式:
if(布爾運算式){
//條件滿足時執行代碼
}
if(布爾運算式){
//條件滿足時執行代碼
}else{
//條件不滿足時執行代碼
}
//多分支
if(布爾運算式){
//條件滿足時執行代碼
}else if(布爾運算式){
//條件滿足時執行代碼
}else{
//條件都不滿足時執行代碼
}
注意:條件運算式必須是布林值
- 示例:
int a = 10;
if(a){
System.out.println(a);
}//err
//對于while等回圈陳述句也一樣
懸垂 else
- 示例:
int x = 10;
int y = 10;
if (x == 10)
if (y == 10)
System.out.println("aaa");
else
System.out.println("bbb");
注:if / else陳述句中可以不加大括號,但只能寫一條陳述句;此時else和最接近的 if 匹配
switch 陳述句
- 基本語法:
switch(整數|列舉|字符|字串){
case 內容1 : {
內容滿足時執行陳述句;
[break;]
}
case 內容2 : {
內容滿足時執行陳述句;
[break;]
}
...
default:{
內容都不滿足時執行陳述句;
[break;]
}
}
- switch(運算式) 中運算式接收的型別包括:
整數(只包括byte、short、int)字符(char)字串(String)列舉型別(區別C語言)
回圈結構
基本上與C語言語法一致
-
注意:
while 回圈
while (運算式) 中的運算式必須是布林值
break :讓最靠近包裹它的整個回圈提前結束
continue :跳過本次回圈,立即進入下次回圈
for 回圈
for(運算式1;運算式2;運算式3) 中的運算式2是回圈的判斷條件,要使用布林值
do while 回圈
while 中的回圈條件只能是布林值
輸入輸出方式
輸出到控制臺
- 基本語法:
System.out.println(msg); // 輸出一個字串,自帶換行
System.out.print(msg); // 輸出一個字串,不帶換行
System.out.printf(format,msg); // 格式化輸出,括號內內容類似于 C 語言的 printf
- 格式化輸出表:
從鍵盤輸入
- 讀取字符/字串/整數/浮點數/布林值
- 首先需要匯入 util 包 import java.util.Scanner;
- 然后再構造一個 Scanner 物件并與”標準輸入流“ System.in 關聯: Scanner 物件名 = new Scanner(System.in);
示例:
import java.util.Scanner;
public class TestDemo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt(); //讀入一個整數
double b = in.nextDouble(); //讀入一個浮點數
boolean c = in.nextBoolean(); //讀入一個布林值
String s = in.next(); //讀入一個字串
//上述讀入字串是按空白符當作分隔符的,故只能讀入第一個空格之前的字符
//如果想要讀取該行的所有字符(包含空格)則:
String s = in.nextLine();
//如果這行代碼上面還有其他讀入的陳述句,可能這行代碼就不會執行
//因為上一行的回車可能被它讀入,直接這行結束
//解決方案:將其放在讀入代碼的第一個或者在它前面加一個 in.nextLine(); 來讀取掉之前的回車
}
}
- 輸入多組資料
示例:
Scanner in = new Scanner(System.in);
while(in.hasNextInt()){
int a = in.nextInt();
// 內容
}
結束:輸入
Ctrl + D或者Ctrl + Z結束
猜數字游戲
- 亂數生成:
需要匯入 util 包
import java.util.Random;
示例:
import java.util.Random;
public class TestDemo {
public static void main(String[] args) {
Random random = new random(); // 默認隨機種子是系統時間
int rand = random.nextInt(bound:100) + 1;
// random.nextInt(bound:100) 是生成[0,100)間的隨機整數
}
}
- 最終代碼:
public class TestDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int rand = random.nextInt(100) + 1;
while (true){
System.out.print("請輸入你所猜測的數字:");
int num = scanner.nextInt();
if(num == rand){
System.out.println("恭喜你,猜對了!");
break;
}else if(num < rand){
System.out.println("很遺憾,你猜的數字小了!");
}else{
System.out.println("很遺憾,你猜的數字大了!");
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/297276.html
標籤:java
下一篇:Java秋招,穩了
