6. แยกย่อย

The Camtasia Studio video content presented here requires JavaScript to be enabled and the latest version of the Macromedia Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

 
รหัสที่ 6-2  ตัวอย่างการแยกคำสั่งรับจำนวนจากผู้ใช้มาเขียนเป็นเมท็อด
import java.util.Scanner;
// โปรแกรมคำนวณดัชนีมวลกาย 
public class BodyMassIndex {
  public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    double weight = readDouble(kb, "น้ำหนัก (kg.) = ");
    double height = readDouble(kb, "ความสูง (cm.) = ");
    double hm = height / 100.0;
    double bmi = weight / (hm * hm);
    System.out.println("ดัชนีมวลกาย = " + bmi);
  }
  public static double readDouble(Scanner kb, String prompt) {
    System.out.print(prompt);
    double value = kb.nextDouble();
    return value;
  }
}
©2009 S.Prasitjutrakul