目錄
- Java流程控制
- Scanner物件
- Scanner類用于獲取用戶的輸入
- java.util.Scanner Jdk5
- next()
- nextLine()
- nextInt() nextDouble()
- 順序結構
- 選擇結構
- if單選擇結構
- if雙選擇結構
- if多選擇結構
- 嵌套if結構
- switch多選擇結構
- 回圈結構
- while回圈
- 死回圈
- do...while回圈
- while和do-while的區別
- for回圈
- 死回圈
- 增強for回圈
- while回圈
- break/continue
- 帶標簽的break/continue
- Scanner物件
Java流程控制
Scanner物件
Scanner類用于獲取用戶的輸入
java.util.Scanner Jdk5
next()
- 一定要讀取到有效字符后才可以結束輸入,
- 對輸入有效字符之前遇到的空白,next()方法會自動將其去掉,
- 只有輸入有效字符后才將其后面輸入的空白作為分隔符或者結束符,
- next()不能得到帶有空格的字串,
package com.qing.scanner;
import java.util.Scanner;
public class Demo01 {
public static void main(String[] args) {
//創建一個Scanner物件,用于接收鍵盤資料
Scanner scanner = new Scanner(System.in);
System.out.println("使用next方式接收:");
//判斷鍵盤是否輸入資料
if (scanner.hasNext()) {
//鍵盤輸入的資料
String next = scanner.next();
System.out.println("輸出的內容為:" + next);
}
//關閉Scanner物件
scanner.close();
}
}
使用next方式接收:
Hello world!
輸出的內容為:Hello
nextLine()
- 以Enter為結束符,nextLine()方法回傳的是輸入回車之前的所有字串,
- 可以獲得空白,
package com.qing.scanner;
import java.util.Scanner;
public class Demo02 {
public static void main(String[] args) {
//創建一個Scanner物件,用于接收鍵盤資料
Scanner scanner = new Scanner(System.in);
System.out.println("使用nextLine方式接收:");
//判斷鍵盤是否輸入資料
if (scanner.hasNextLine()) {
//鍵盤輸入的資料
String nextLine = scanner.nextLine();
System.out.println("輸出的內容為:" + nextLine);
}
//關閉Scanner物件
scanner.close();
}
}
使用nextLine方式接收:
Hello World!
輸出的內容為:Hello World!
nextInt() nextDouble()
順序結構
- 按照順序依次執行,
- Java的基本結構就是順序結構,
- 順序結構是最簡單的演算法結構,
- 任何一個演算法都離不開的一種基本演算法結構,
選擇結構
if單選擇結構
if (i > 10) {}
if雙選擇結構
if (i > 10) {
} else {}
if多選擇結構
if (i > 10) {
} else if (i < 0) {
} else {}
嵌套if結構
if (i > 10) {
if (j > 10) {}
}
switch多選擇結構
- switch陳述句中的變數型別可以是:byte short int char String
- case標簽必須是字串常量或字面量,
- case穿透,
- IDEA反編譯,
package com.qing.struct;
public class SwitchDemo01 {
public static void main(String[] args) {
char grade = 'C';
switch (grade) {
case 'A':
System.out.println("優秀");
break;
case 'B':
System.out.println("良好");
break;
case 'C':
System.out.println("及格");
break;
default:
System.out.println("不及格");
}
}
}
回圈結構
while回圈
int i = 0;
while (i < 100) {
System.out.println(++i);
}
死回圈
while (true) {
//回圈內容
}
do...while回圈
int i = 0;
do {
System.out.println(++i);
} while (i < 100)
while和do-while的區別
- while先判斷后執行,do-while先執行后判斷,
- do-while總是保證回圈體至少執行一次,
for回圈
死回圈
for (;;) {
//回圈體
}
增強for回圈
int[] array = {1,2,3,4,5};
for (int x : array) {
System.out.println(x);
}
break/continue
- break 退出回圈
- continue 跳過本次回圈,繼續下次回圈
帶標簽的break/continue
outer:for () {
for () {
if () {
break outer;
}
}
}
outer:for () {
for () {
if () {
continue outer;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/195917.html
標籤:Java
