125
tillarida konstantlarni #define direktivasi yoki Pascal / Delphi tillarida const kalit
so‘zi yordamida berishga mosdir.
Agar interfeys o‘z ichiga usullarni olmasa, interfeys realizatsiyasi deb e’lon
qilingan sinf xech narsa realizatsiya qilmaydi. Konstantalarni sinf nomlar fazosiga
import qilish uchun final modifikatorli o‘zgaruvchilardan foydalanish qulaydir.
import java.util.Random;
interface SharedConstants { int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int SOON = 4;
int NEVER = 5; }
class Question implements SharedConstants {
Random rand = new Random();
int ask() {
int prob = (int) (100 * rand.nextDouble());
if (prob < 30) return NO; // 30%
else if (prob < 60) return YES; // 30%
else if (prob < 75) return LATER; // 15%
else if (prob < 98) return SOON; // 13%
else
return NEVER; // 2% } }
class AskMe implements SharedConstants {
static void answer(int result) {
switch(result) {
case NO:
System.out.println("No");
break;
case YES:
System.out.println("Yes");
126
break;
case MAYBE:
System.out.println("Maybe");
break;
case LATER:
System.out.println("Later");
break;
case SOON:
System.out.priniln("Soon");
break;
case NEVER:
System.out.println("Never");
break;
} }
public static void main(String args[]) {
Question q = new Question();
answer(q.ask());
answer(q.ask());
answer(q.askO);
answer(q.ask());
} }
E’tibor berinki dastur xar gal ishlatilganda xar xil natija beradi, chunki unda
java.util paketiga tegishli Random tasodifiy sonlar generator ishlatilgan.
S:\> Java AskMe
Later
Scon
No
Yes
Dostları ilə paylaş: