1. 程式人生 > 其它 >Scanner和選擇結構、迴圈結構。順序結構

Scanner和選擇結構、迴圈結構。順序結構

流程控制

Scanner

通過Scanner類獲取使用者的輸入

public class HelloWord {
   public static void main(String[] args){
       Scanner a = new Scanner(System.in);
       System.out.println("使用next接受輸入資訊:");
       //判斷使用者是否輸入字串
       if (a.hasNext()){
           String str = a.next();//程式會等待使用者輸入完畢
           System.out.println("使用next()輸出的內容為:"+str);
      }
     /* 使用next接受輸入資訊:
         Hello Word!
         使用next()輸出的內容為:Hello*/
       //用完關掉 節省資源
       a.close();
       System.out.println("使用nextLine接收");
       Scanner b = new Scanner(System.in);

       if (b.hasNext()){
           String str2 = b.nextLine();
           System.out.println("使用nextLine輸出的內容為:"+str2);
      }
       b.close();
    /*   Hello word!
           使用nextLine輸出的內容為:Hello word!*/
  }
}
next():
  1. 一定要讀取到有效字元後才可以結束輸入

  2. 對輸入有效字元之前遇到的空白,next()將自動將其去掉

  3. 只有輸入有效字元後才將其後面輸入的空白作為分隔符或者結束符

  4. next()不能去掉帶有空格的字串

nextLine():
  1. 以Enter為結束符 也就是說:nextLine()方法返回的是輸入回車之前的所有的字元

  2. 可以獲得空白

順序結構

java的基本結構。是任何一個演算法都離不開的一種基本演算法。

選擇結構

if單選擇結構
if(){
   
}

 

if雙選擇結構
if(){
   
}else{
   
}

 

if多選擇結構
if(){

}else if{

}else if{

}else{

}

 

巢狀的if結構
if(){
   if(){
       
  }
}

 

switch多選擇結構

判斷 一個變數一系列值中的某個值 是否相等,每個值稱為一個分支。

switch語句中變數型別可以是byte、short、int、char

javaSE7 支援String

同時 case 標籤必須為 字串常量或字面量

 char score = 'F';
      switch (score){
          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;
      int sum = 0;
      while(i<=100){
          sum = sum + i;

          if (i == 100){
              System.out.println(sum);
          }
          i++;
      }

 

do........while迴圈

while 和 do whie的區別?

while先判斷後執行

do...while 先執行後判斷,至少執行一次

 int a = 0;
   while(a<0){
       System.out.println(a);
       a++;
  }
       System.out.println("=================");
   do {
       System.out.println(a);
       a++;
  }while(a<0);
//控制檯輸出
//=================
//0

 

for迴圈

for是最有效最靈活的迴圈結構;

IDER 快捷鍵 100.for

for(int i = 0;i<100;i++){
   
}

 

增強型for迴圈