Skip to main content
Here is the next Java program you’ll enter, which introduces you to the if statement. Type this in, make it run exactly right and then we’ll see if your practice has paid off.
WhatIf.java
public class WhatIf
{
    public static void main( String[] args )
    {
        int people = 20;
        int cats = 30;
        int dogs = 15;

        if ( people < cats )
        {
            System.out.println( "Too many cats!  The world is doomed!" );
        }

        if ( people > cats )
        {
            System.out.println( "Not many cats!  The world is saved!" );
        }

        if ( people < dogs )
        {
            System.out.println( "The world is drooled on!" );
        }

        if ( people > dogs )
        {
            System.out.println( "The world is dry!" );
        }

        dogs += 5;

        if ( people >= dogs )
        {
            System.out.println( "People are greater than or equal to dogs." );
        }

        if ( people <= dogs )
        {
            System.out.println( "People are less than or equal to dogs." );
        }

        if ( people == dogs )
        {
            System.out.println( "People are dogs." );
        }
    }
}
Make a program which displays a different message depending on the age given. Here are the possible responses:
  • age is less than 16, say “You can’t drive.”
  • age is less than 18, say “You can’t vote.”
  • age is less than 25, say “You can’t rent a car.”
  • age is 25 or over, say “You can do anything that’s legal.”
Here’s a sample run. Notice that a person who is under 16 will display three messages, one for being under 16, one for also being under 18, and one for also being under 25.Sample Output:
Hey, what's your name? Billy_Corgan

Ok, Billy_Corgan, how old are you? 17

You can't vote, Billy_Corgan.
You can't rent a car, Billy_Corgan.
Type this one in and make it work, too.
ElseAndIf.java
public class ElseAndIf
{
    public static void main( String[] args )
    {
        int people = 30;
        int cars = 40;
        int buses = 15;

        if ( cars > people )
        {
            System.out.println( "We should take the cars." );
        }
        else if ( cars < people )
        {
            System.out.println( "We should not take the cars." );
        }
        else
        {
            System.out.println( "We can't decide." );
        }

        if ( buses > cars )
        {
            System.out.println( "That's too many buses." );
        }
        else if ( buses < cars )
        {
            System.out.println( "Maybe we could take the buses." );
        }
        else
        {
            System.out.println( "We still can't decide." );
        }

        if ( people > buses )
        {
            System.out.println( "All right, let's just take the buses." );
        }
        else
        {
            System.out.println( "Fine, let's stay home then." );
        }

    }
}
I have provided a function that is supposed to return the name of a day of the week given the day number.Files NeededUse if and else to complete it according to the following table:
NumberDay of week
1Sunday
2Monday
3Tuesday
4Wednesday
5Thursday
6Friday
7Saturday
0Saturday
anything else"error"
Using if statements, else if, and else statements, make a program which displays a different message depending on the age given.
AgeMessage
less than 16"You can't drive."
16 to 17"You can drive but not vote."
18 to 24"You can vote but not rent a car."
25 or older"You can do pretty much anything."
Note that unlike the original “How Old Are You” assignment, this program must only display exactly one message for a given age and not multiple messages. Sample Output:
Hey, what's your name? (Sorry, I keep forgetting.) Billy_Corgan
Ok, Billy_Corgan, how old are you? 17

You can drive but you can't vote, Billy_Corgan.
Hey, what's your name? (Sorry, I keep forgetting.) Billy_Corgan
Ok, Billy_Corgan, how old are you? 14

You can't drive, Billy_Corgan.
You can make up your own messages if you want, but you must have at least four messages, and you must use else if statements to make sure only one of the messages is printed for any given age.
Julio Cesar Chavez Mark VII is an interplanetary space boxer, who currently holds the championship belts for various weight categories on many different planets within our solar system. However, it is often difficult for him to recall what his “target weight” needs to be on earth in order to make the weight class on other planets. Write a program to help him keep track of this.It should ask him what his earth weight is, and to enter a number for the planet he wants to fight on. It should then compute his weight on the destination planet based on the table below:
#PlanetRelative gravity
1Venus0.78
2Mars0.39
3Jupiter2.65
4Saturn1.17
5Uranus1.05
6Neptune1.23
So, for example, if Julio weighs 128 lbs. on earth, then he would weigh just under 50 lbs. on Mars, since Mars’ gravity is 0.39 times earth’s gravity. (128 * 0.39 is 49.92)
Please enter your current earth weight: 128

I have information for the following planets:
    1. Venus   2. Mars    3. Jupiter
    4. Saturn  5. Uranus  6. Neptune

Which planet are you visiting? 2

Your weight would be 49.92 pounds on that planet.
Write an interactive quiz. It should ask the user three multiple-choice or true/false questions about something. It must keep track of how many they get wrong, and print out a “score” at the end.
Are you ready for a quiz?  N
Okay, here it comes!

Q1) What is the capital of Alaska?
    1) Melbourne
    2) Anchorage
    3) Juneau

> 3
That's right!

Q2) Can you store the value "cat" in a variable of type int?
    1) yes
    2) no

> 2
Sorry, "cat" is a string. ints can only store numbers.

Q3) What is the result of 9+6/3?
    1) 5
    2) 11
    3) 15/3

> 2
That's correct!

Overall, you got 2 out of 3 correct.
Thanks for playing!
In this program, you’ll use a loop to draw a simple ASCII-based animation on the screen, and you will use modulus (%) to determine which frame of the animation to show. (You will learn how to create your own loops later.)Files NeededIf you download, compile and run ModulusAnimationWorm.java it will look roughly like this.
********
(It will look cooler while it’s running.)
Make a program which plays a simple game of 20 2 Questions. The first question should be “animal, vegetable, or mineral?” Then, the second question should be “is it bigger than a breadbox?” Then, display one of six possible responses, depending on their answers. You can choose what answers to give for each of the six possibilities.Here’s a suggestion:
size \ typeanimalvegetablemineral
smaller than a breadboxsquirrelcarrotpaper clip
bigger than a breadboxmoosewatermeloncamaro
You will use nested if statements to do this. Sample Output:
TWO QUESTIONS!
Think of an object, and I'll try to guess it.

Question 1) Is it animal, vegetable, or mineral?
> animal

Question 2) Is it bigger than a breadbox?
> no

My guess is that you are thinking of a mouse.
I would ask you if I'm right, but I don't actually care.
TWO QUESTIONS!
Think of an object, and I'll try to guess it.

Question 1) Is it animal, vegetable, or mineral?
> mineral

Question 2) Is it bigger than a breadbox?
> yes

My guess is that you are thinking of a truck.
I would ask you if I'm right, but I don't actually care.
TWO QUESTIONS!
Think of an object, and I'll try to guess it.

Question 1) Is it animal, vegetable, or mineral?
> vegetable

Question 2) Is it bigger than a breadbox?
> yes

You're thinking of a pumpkin!
I would ask you if I'm right, but I don't actually care.
Make a short “Choose Your Own Adventure” game. The starting room should give the user two choices. Then the second room they travel to should give them two more choices. Finally the third room should give them two choices.This means your game will have eight possible “endings”. Your game will also have a total of fifteen rooms:You must use nested if statements to do this. Sample Output:
WELCOME TO MITCHELL'S TINY ADVENTURE!

You are in a creepy house!  Would you like to go "upstairs" or into the
"kitchen"?
> kitchen

There is a long countertop with dirty dishes everywhere.  Off to one side
there is, as you'd expect, a refrigerator. You may open the "refrigerator"
or look in a "cabinet".
> refrigerator

Inside the refrigerator you see food and stuff.  It looks pretty nasty.
Would you like to eat some of the food? ("yes" or "no")
> no

You die of starvation... eventually.
WELCOME TO MITCHELL'S TINY ADVENTURE!

You are in a creepy house!  Would you like to go "upstairs" or into the
"kitchen"?
> upstairs

Upstairs you see a hallway.  At the end of the hallway is the master
"bedroom".  There is also a "bathroom" off the hallway.  Where would you like
to go?
> bedroom

You are in a plush bedroom, with expensive-looking hardwood furniture.  The
bed is unmade.  In the back of the room, the closet door is ajar.  Would you
like to open the door? ("yes" or "no")
> no

Well, then I guess you'll never know what was in there.  Thanks for playing,
I'm tired of making nested if statements.
Using if statements with compound conditions (like &&), make a program that displays a single message depending on the age given.
AgeMessage
less than 1 6"You can't drive."
16 to 17"You can drive but not vote."
18 to 24"You can vote but not rent a car."
25 or older"You can do pretty much anything."
This output of this assignment is identical to the “How Old Are You, Specifically” assignment. However, this time you must accomplish it using if statements with compound conditions and you must not use else if or else.
Sample Output:
Your name: Dukes
Your age: 19

You can vote but you can't rent a car, Dukes.
Your name: Dukes
Your age: 12

You can't drive, Dukes.
You can make up your own messages if you want, but you must have at least four messages, and you must use && statements to make sure only one of the messages is printed for any given age.
Using if statements with compound conditions (like &&), make a guessing game of two questions similar to the Twenty Questions assignment.However, this time you must accomplish it using if statements with compound conditions and you must not use else if or else or nested ifs.
  • Question 1: Does it belong inside or outside or both?
  • Question 2: Is it alive?
Again, here are some sample responses, for the non-creative among you.
insideoutsideboth
alivehouseplantbisondog
not aliveshower curtainbillboardcell phone
Sample Output:
TWO MORE QUESTIONS, BABY!

Think of something and I'll try to guess it!

Question 1) Does it stay inside or outside or both? outside
Question 2) Is it a living thing? yes

Then what else could you be thinking of besides a python?!?
TWO MORE QUESTIONS, BABY!

Think of something and I'll try to guess it!

Question 1) Does it stay inside or outside or both? both
Question 2) Is it a living thing? no

Obviously the nonliving, inside/outside thing on your mind is a dead ant!
(This assignment was suggested by Joel H in 2012.)The body mass index (BMI) is commonly used by health and nutrition professionals to estimate human body fat in populations. It is computed by taking the individual’s weight (mass) in kilograms and dividing it by the square of their height in meters.Start with the BMI Calculator you wrote previously (BMICalc.java). Then use some if statements to show the category for a given BMI.
BMICategory
less than 18.5underweight
18.5 to 24.9normal weight
25.0 to 29.9overweight
30.0 or moreobese
Although BMI is a very good estimate of human body fat, the formula doesn’t work well for athletes with a lot of muscle, or people who are extremely short or very tall. If you are concerned about your BMI, check with your doctor.
Sample Output:
Your height in m: 1.75
Your weight in kg: 73

Your BMI is 23.83673
BMI Category: normal weight
It doesn’t matter whether you input the values in metric (kilos and meters) or Imperial measurements (feet/inches and pounds).
Your height in inches: 69
Your weight in pounds: 220

Your BMI is 32.5
BMI Category: obese
Make a program which displays an appropriate name for a person, using a combination of nested ifs and compound conditions. Ask the user for a gender, first name, last name and age.If the person is female and 20 or over, ask if she is married. If so, display “Mrs.” in front of her name. If not, display “Ms.” in front of her name. If the female is under 20, display her first and last name.If the person is male and 20 or over, display “Mr.” in front of his name. Otherwise, display his first and last name.Note that asking a person if they are married should only be done if they are female and 20 or older, which means you will have a single if and else nested inside one of your if statements.Also, did you know that with an if statement (or else), the curly braces are optional when there is only one statement inside? Sample Output:
What is your gender (M or F): F
First name: Kim
Last name: Kardashian
Age: 32

Are you married, Kim (y or n)? y

Then I shall call you Mrs. Kardashian.
What is your gender (M or F): F
First name: Marisa
Last name: Tomei
Age: 48

Are you married, Marisa (y or n)? n

Then I shall call you Ms. Tomei.
Notice that in the example below, we never even ask the marriage question, because she is under 20 and so her marital status doesn’t change what we call her.
What is your gender (M or F): F
First name: Chloe
Last name: Moretz
Age: 16

Then I shall call you Chloe Moretz.
What is your gender (M or F): M
First name: Daniel
Last name: Radcliffe
Age: 23

Then I shall call you Mr. Radcliffe.
What is your gender (M or F): M
First name: Zachary
Last name: Gordon
Age: 15

Then I shall call you Zachary Gordon.
Write a program that compares several Strings using the compareTo() method. You should display the Strings and display the integer that compareTo() gives you.You must have five examples which result in a number less than 0, five examples which result in a number greater than 0, and two examples which give you exactly 0. This means you need a total of twelve examples.You may not just flip the Strings around; you must have twelve different examples.Here’s an example:
CompareToChallenge.java
System.out.print("Comparing \"axe\" with \"dog\" produces ");
int i = "axe".compareTo("dog");
System.out.println(i);

System.out.print("Comparing \"applebee's\" with \"apple\" produces ");
System.out.println( "applebee's".compareTo("apple") );
Sample Output:
Comparing "axe" with "dog" produces -3
Comparing "applebee's" with "apple" produces 5
Make a program that asks for the last name of the user. Depending on their last name, make a statement about how long they have to wait during roll call. You need to use else ifs to make sure only one statement gets printed.Once you understand how compareTo() works, this is a pretty straightforward assignment, much like How Old Are You, specifically, except that it uses Strings instead of ints and so you must use the compareTo() method.
  • name is "Carswell" or before: say “you don’t have to wait long”
  • name is "Jones" or before: say “that’s not bad”
  • name is "Smith" or before: say “looks like a bit of a wait”
  • name is "Young" or before: say “it’s gonna be a while”
  • name is after "Young": say “not going anywhere for a while?”
Sample Output:
What's your last name? Stephanopolis
It's going to be a while before we get to you, "Stephanopolis".
Write a program that plays an incredibly stupid number-guessing game. The user will get one try to guess the secret number. Tell them if they got it right or wrong, and if they got it wrong, display what the secret number was.You must store the secret number in a variable, and use that variable throughout. The secret number itself must not appear in the program at all, except in the one line where you store it into a variable.I know it will be the same number every time the game is played.Sample Output:
TEH WORST NUBMER GESSING GAME EVAR!!!!!!!1!

I"M THKING OF A NBR FROM 1-10.  TRY 2 GESS! 3

W00T!  U SUX0R!!!  I PWN J00!!!  IT WAS 4!
TEH WORST NUBMER GESSING GAME EVAR!!!!!!!1!

I"M THKING OF A NBR FROM 1-10.  TRY 2 GESS! 4

LOL!!! U GOT IT!  I CANT BELEIVE U GESSED IT WAS 4!
TEH WORST NUBMER GESSING GAME EVAR!!!!!!!1!

I"M THKING OF A NBR FROM 1-10.  TRY 2 GESS! 4

LOL!!! U GOT IT!  I CANT BELEIVE U GESSED IT WAS 4!
TEH WORST NUBMER GESSING GAME EVAR!!!!!!!1!

I"M THKING OF A NBR FROM 1-10.  TRY 2 GESS! 4

LOL!!! U GOT IT!  I CANT BELEIVE U GESSED IT WAS 4!

/me walks away shaking his head....