Java學習 (五)、條件結構,java學習條件結構

來源:互聯網
上載者:User

Java學習 (五)、條件結構,java學習條件結構

一、if...else語句

1 //匯入包使用Scanner 2 import java.util.Scanner; 3 public class IfDemo{ 4 public static void main(String [] args){ 5 Scanner input=new Scanner(System.in); 6 System.out.println("請輸入假期天數"); 7 int holiday=input.nextInt();//擷取鍵盤輸入的整數 next表示字串 nextDouble表示double類型 8 if(holiday>6) 9 {10 System.out.println("去海南");11 }12 else if(holiday>3)13 {14 System.out.println("去海邊");15 }16 else17 {18 System.out.println("在家");19 }20 }21 }View Code

二、switch

1 import java.util.Scanner; 2 public class SwitchDemo{ 3 public static void main(String []args) 4 { 5 Scanner input=new Scanner(System.in); 6 System.out.println("請輸入1-5之間的數字"); 7 int number=input.nextInt(); 8 switch(number) 9 {10 case 1:System.out.println("1");break;11 case 2:System.out.println("2");break;12 case 3:System.out.println("3");break;13 case 4:System.out.println("4");break;14 case 5:System.out.println("5");break;15 default:System.out.println("Error");break;16 }17 }18 }View Code

小結

1.case後面的常量不能重複
2.break可以省略,一旦省略,程式就會一直往下執行,直到遇見break或switch結束
3.case的順序可以顛倒,default可以放在任何位置,一般放在最後,可以省略
4.switc用於匹配常量,能匹配的類型有byte,short,int,char,String(jdk1.7及以上),enum(jdk1.5)
5.switch和多重if...else語句比較
switch適合做等值判斷,不適合做區間判斷,做等值判斷的時候文法更簡潔,直觀
多重if語句功能比switch更全面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.