輸入&輸出
輸入
從控制台擷取輸入,需要導入
Java
中的
java.util.Scanner
類,通過讀取對應類型來擷取不同類型輸入;
package note3;
/**
* Created with IntelliJ IDEA.
* Version : 1.0
* Author : cunyu
* Email : [email protected]
* Website : https://cunyu1943.github.io
* Date : 2019/12/18 17:30
* Project : JavaLeaning
* Package : note3
* Class : InputAndOutput
* Desc : Java筆記3
*/
import java.util.Scanner;
public class InputAndOutput {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// 輸入整行并擷取字元串
System.out.println("Input the name");
String strName = input.nextLine();
// 輸入整行并擷取整數
System.out.println("Input the id");
int intId = input.nextInt();
System.out.println("Name is : " + strName);
System.out.println("Id is : " + intId);
}
}
複制
輸出
-
普通輸出
通過
即可不換行輸出,而System.out.print
則是輸出并換行;System.out.println
-
格式化輸出
通過占位符,将數組類型“格式化”為指定字元串,常用占位符如下表,注意
表示占位符,要輸出%
則需要使用兩個連續%
%%
:
占位符說明%d格式化輸出整數%x格式化輸出十六進制整數%f格式化輸出浮點數%e格式化輸出科學計數法表示的浮點數%s格式化字元串
if判斷
- 基本文法
if (condition)
{
// do something if condition is true...
...
}
複制
if(condition)
{
// do something if condition is true...
...
} else
{
// do something if condition is false...
}
複制
-
引用類型和引用類型的變量内容相等判斷
public class Main() { public static void main(String[] args) { String s1 = "hello"; String s2 = "hello"; if(s1 == s2) { System.out.println("s1 == s2"); } // s1若為null,會報錯 NullPointerException if(s1.equals(s2)) { System.out.println("sq equals s2"); } } }
-
:用于判斷引用類型是否相等,用于判斷兩個對象是否指向同一對象;==
-
:用于判斷引用類型的變量内容是否相等;equals()
-
switch多重選擇
switch (option) {
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
default:
break;
}
複制
其中,
option
的資料類型可以必須是 整形、字元串或枚舉型 類型,PS:千萬不要忘了
break
和
default
;
while & do while循環
-
while
:即讓計算機根據條件做循環計算,在滿足條件時繼續循環,條件不滿足時退出循環。在每次循環前,先判斷條件是否成立,成立則執行循環體内語句,否則直接跳出循環;
while(condition) { // 循環語句 } // 繼續執行後續代碼
-
do...while
:先執行循環,再判斷條件,條件滿足則繼續循環,不滿足時退出循環,至少會循環一次;
do{ // 執行循環語句 } while(condition);
for循環
-
利用計數器實作循環,先初始化計數器,然後在每次循環前檢測循環條件,經每次循環後更新計數器;
for(初始條件;循環檢測條件;循環後更新計數器) { // 循環執行語句 }
-
for
循環可以缺少初始化語句、循環條件和每次循環更新語句;
// 不設結束條件 for(int i = 0; ; i++){ ... }
// 不設結束條件和更新語句 for(int i = 0; ;){ ... }
// 三者均不設定 for( ; ; ){ ... }
-
for each
循環:用于周遊所有“可疊代”的資料類型,其循環的變量非計數器,而是對應數組中的每個元素,但同時它無法指定周遊順序,也無法擷取數組索引;
// for 和 for each循環數組 int[] array = {1,3,5,7,9}; // for for(int i = 0; i < array.length; i++){ System.out.println(array[i] + "\t"); } // for each for(int n: array){ System.out.println(n + "\t"); }
**PS:**計數器變量定義在
循環内部,循環體内部不修改計數器;for
break和continue
-
break
:
循環過程中用于跳出目前循環,常搭配
if
使用,總是跳出其所在的那一層循環;
public class Main{ public static void main(String[] args){ int sum = 0; for(int i = 0; ; i++){ sum += i; if(i == 100){ break; } } System.out.println(sum); } }
-
提前結束本次循環,直接進行下一次循環,常搭配continue
if
使用,滿足條件時提取結束當次循環;
public class Main{ public static void main(String[] args){ int sum = 0; for(int i = 0; i <= 100; i++){ sum += i; // 計算1 + 2 + 3 + ... + 100的和,但是其中要減去 10 if(i == 10){ continue; } } System.out.println(sum); } }
總結
本文章總結了流程控制中的輸入輸出、
if
、
switch
、單重和多重循環以及跳出及終止循環的相關知識;