if, probably one of the most typed things in programming. It is basically a question.
For example, is bob a mango?
if(bob == mango)
is how in java you pose that question, after that you put is what happens if the answer is yes, bob is a mango.
if(bob == mango){
System.out.println("Bob is indeed a mango, good for him");
} else {
System.out.println("Bob had been found not to be a mango");
}
But what if Bob is really a pomegranate?
if(bob == mango){
System.out.println("Bob is indeed a mango, good for him");
} else if(bob == pomegranate {
System.out.println("Bob had been found not to be a mango but to be a pomegranate spy!");
} else {
System.out.println("We have no idea what bob is");
}
the else if is another question, it gets asked after the first one. The else is what happens when the question returns false.
for ints, longs, float, double and char the question is ==
for Strings it is bob.equals(mango)
Now for For
for is a command, do this x number of times.
int i, potatoesNeededToBePlanted = 10;
for(i = 0; i < potatoesNeededToBePlanted; ++i){
// plant potato
System.out.println("potato planted");
}
Would output “potato planted” 10 times,
It goes like this
i = 0,
if i is below to potatoesNeededToBePlanted then
print out “potato planted”
increment i
return to if statement
These are very useful when you know how many times something needs to be done, but what if you do not know how many times it should happen? That’s when a Do While or While loop is called upon.
do While loops happen at least once and a While loop may never get called upon. Each has their own use.
do{
// stuff goes in here, such as user input that can be another question, like how many potatoes are left
}while(potatosLeft != 0);
while(potatoesLeft != 0){
// this may not run if the potatoesLeft variable is set to 0 before it reaches this loop
}
!= means does not equal to, the other operands are
> greater then
< smaller then
>= greater or equal to
< = smaller or equal to
Well I hope this is of use to someone, if you have any questions, then feel free to leave a comment
Heres a picture of brian too
the office dog / programmer.




Recent Comments