Sunday, October 10, 2010

8. The if and else statement

Okay so now that you can read input from the user and do loops and you know about variables and all sorts of stuff it's time to learn about if statements and these things are awesome.  So here a quick example of an if statment:
if(I am hungry) {
    eat food;
}
Basically you just check if something is true and if it is then you do whatever follows.  Fairly simple.  So lets use the user input program that we had, if you don't have it you can follow tutorial #7 and that should catch you up or you can download the code from the source code page on my site.  Anyways, open up the Userstuff java program and change it to this:
import java.util.Scanner;

public class Userstuff
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.print("Please input your name and then click enter: ");
        String name = input.nextLine();
        System.out.print("Please input you age and then click enter: ");
        int age = input.nextInt();
        System.out.println("Hello " + name + " you are " + age + " years old");
        if (age < 16) {
            System.out.print(" and you're still a kid!");
        }
    }
}
So here we are just asking for the name and age, printing it out, and then checking if the person is still a kid.  If they are then you print out "and you're still a kid!"  This is pretty straightforward and pretty simple, maybe too simple.  What about if they are older than 16, you could do a second if statement but that just seems too complicated.  Luckily java already has an answer and is the else statement, lets use my earlier example to explain it better!
if(I am hungry) {
    eat food;
 
else {
    don't eat food;
 
So here we check if I am hungry, if I am I eat food but if I'm not I don't eat food.  So lets use this else statement for the Userstuff program.  After the if statement add this:
else {
    System.out.print(" and you now have responsibilities!");
 
A little insulting but that's not the point.  Now our program will print out " and you now have responsibilities!" if the person is 16 or older.  

So now that you know about the if statement try to make a simple game.  Something where people try to guess a number and you could tell them whether it's too high or too low using if statements!

By the way, I have not made a tutorial about using > or < signs and checking if things are true or not.  I will make a tutorial about these next and maybe one about random numbers so we can make a sweet number guessing game!  See you next time! 

2 comments:

  1. can you also av sumfin lyk this

    else if(age>40 && age<50)
    {
    System.out.println("you are in the working class now");
    }

    else
    {
    System.out.println("still a youth");
    }

    ReplyDelete