3. ทำซ้ำ ๆ

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.

 
รหัสที่ 3-13  โปรแกรมหาค่าเฉลี่ยของชุดข้อมูลที่เป็นจำนวนบวก (ให้ค่า <= 0 ถือว่าข้อมูลหมดแล้ว)
import java.util.Scanner;
// โปรแกรมหาค่าเฉลี่ย (ผู้ใช้ให้ค่า 0 หรือน้อยกว่า  ถือว่าหมด)
public class Average3 {
  public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    double sum = 0;
    int k = 0;  // k ไว้นับจำนวนข้อมูล 
    while (true) {
      System.out.print("จำนวนที่ " + (k+1) + " = ");
      double v = kb.nextDouble();
      if (v <= 0) break; // หลุดจากวงวน เมื่อข้อมูลหมดแล้ว 
      sum += v;
      k++;          
    }
    System.out.println("ค่าเฉลี่ย = " + (sum / k));
  }
}
©2009 S.Prasitjutrakul