4. เลือกปฏิบัติ

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.

 
รหัสที่ 4-21  โปรแกรมเกมทายตัวเลข
import java.util.Scanner;
// โปรแกรมเกมทายตัวเลข 
public class WhatsThatNumber {
  public static void main(String[] args) {
    System.out.println("เกมทายตัวเลข : คุณมีโอกาส 7 ครั้ง");    
    System.out.println("ทายว่าผมนึกถึงจำนวนใดอยู่ (1-100)");
    Scanner kb = new Scanner(System.in);
    int myNumber = 1 + (int)(100 * Math.random());
    int k = 1;
    boolean correct = false;
    while (true) {
      if (correct || k > 7) break;
      System.out.print("การทายครั้งที่ " + k + " : ");
      int yourGuess = kb.nextInt();
      correct = (yourGuess == myNumber);
      if (myNumber < yourGuess) System.out.println("น้อยกว่า");
      if (myNumber > yourGuess) System.out.println("มากกว่า");
      k++;
    }
    if (correct) {
      System.out.println("ถูกต้องแล้วครับ");
    } else {
      System.out.println("เสียใจครับ");
      System.out.println("ผมกำลังนึกถึง " + myNumber + " ครับ");
    }
  }
}
©2009 S.Prasitjutrakul