Java basic | Java OOP | โครงสร้างข้อมูล | โจทย์ ACM



[Java]การใช้ switch case

1 comment
      

               I have the source code.


/** ตัวอย่างการใช้งาน switch case
 * ตัวอย่างนี้ เป็นการแปลงตัวเลขเป็นตัวอักษร โดยนำ   switch case มาใช้งาน
 *
 * @author http://javaagkasit.blogspot.com/
 */
public class switchCase {
    public static void main(String [] args){
        for(int i = 0 ; i < 10 ; i++){
            System.out.println(revertNumberToString(i));//Show  Number String
        }
    }
    //Mathode revert Number to String.
    public static String revertNumberToString(int i){
        switch(i){
            case 0 : return "zero";     //if i == 0  then return "zero"
            case 1 : return "one";      //if i == 1  then return "one"
            case 2 : return "two";      //if i == 2  then return "two"
            case 3 : return "tree";     //if i == 3  then return "tree"
            case 4 : return "four";     //if i == 4  then return "four"
            case 5 : return "five";     //if i == 5  then return "five"
            case 6 : return "six";      // .
            case 7 : return "seven";    // .
            case 8 : return "eigth";    // .
            case 9 : return "nine";     //if i == 9  then return "nine"
            default : return"ten";      //others in condition then == "ten"
         
    }
    }
}
         
           สาเหตุที่ไม่มีคำสัง break  เหมือน switch case แบบที่เราเคยเห็นทั่วไป คือ ในลักษณะการทำงานนี้ทำครั้งเดียวอยู่แล้วไม่จำเป็นต้อง ใช้คำสั่ง break

          Explained by this.

       

         Output.



share

1 comment :

  1. คืออยากทำให้มันรับค่าจะต้องใช้คำสั่งอะไรคะ

    ReplyDelete