Saturday, October 13, 2012

How to use variable and use that variable till end of number..............



The perfect program to learn variables.



public class Pepsi {


public static void main(String[] args) {


int bottleNum = 10;

String word = "bottles";


while (bottleNum > 0) {


if(bottleNum==1){


word = "bottle";

}

System.out.println(bottleNum + " "+ word + " of pepsi left in freezer!!!");


System.out.println(bottleNum + " "+ word+ "of bottle.");


System.out.println("Now what??????");


bottleNum = bottleNum -1;

if (bottleNum > 0) {


System.out.println("Keep drinking and make world record");

}
               else {
System.out.println("NOW STOP DRINKING PEPSI, TRY SOMETHING ELSE..........");
}
}
}
}

_________________________________________________________________________________

Output:


10 bottles of pepsi left in freezer!!!
10 bottlesof bottle.
Now what??????
Keep drinking and make world record
9 bottles of pepsi left in freezer!!!
9 bottlesof bottle.
Now what??????
Keep drinking and make world record
8 bottles of pepsi left in freezer!!!
8 bottlesof bottle.
Now what??????
Keep drinking and make world record
7 bottles of pepsi left in freezer!!!
7 bottlesof bottle.
Now what??????
Keep drinking and make world record
6 bottles of pepsi left in freezer!!!
6 bottlesof bottle.
Now what??????
Keep drinking and make world record
5 bottles of pepsi left in freezer!!!
5 bottlesof bottle.
Now what??????
Keep drinking and make world record
4 bottles of pepsi left in freezer!!!
4 bottlesof bottle.
Now what??????
Keep drinking and make world record
3 bottles of pepsi left in freezer!!!
3 bottlesof bottle.
Now what??????
Keep drinking and make world record
2 bottles of pepsi left in freezer!!!
2 bottlesof bottle.
Now what??????
Keep drinking and make world record
1 bottle of pepsi left in freezer!!!
1 bottleof bottle.
Now what??????
NOW STOP DRINKING PEPSI, TRY SOMETHING ELSE..........
_____________________________________________________________________

First of all you need tool to compile this program and according me eclipse is the best tool for compile JAVA program. You can download it from internet.


The above program showing us that how to use variable in different manner and how to use if and else. We are taking pepsi as class and bottleNum and bottles as variable. Here we have 99 bottles of pepsi and we will finish it till it reach to 1.


In this program you can also see that we are using "bottles" word until it is more than 1, If it is only 1 (one) bottle left than it called "bottle" only, not "bottles".


And with use of If and else we can print out the message after finishing all bottles.



You can copy and paste this code but if you start write this code manually than, it really help you to remember this methods. Try it on your own than tell me the difference !

Thank you for viewing this post.........

No comments:

Post a Comment