Documentation Index
Fetch the complete documentation index at: https://v1-learn.neoartd.my.id/llms.txt
Use this file to discover all available pages before exploring further.
21. What If - Link
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.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." );
}
}
}
U:\My Documents\CompSci\>java WhatIf
Too many cats! The world is doomed!
The world is dry!
People are greater than equal to dogs.
People are less than equal to dogs.
People are dogs.
U:\My Documents\CompSci\>
Assignments turned in without these things will not receive any points.In this section, you’re going to try to guess what you think the if statement is and what it does.
- What do you think the if does to the code under it? Put your answer in a comment in the code.
Answer : If statement is a conditional statement that runs the code under it if the condition is true.
- What is the purpose of the curly braces in the if statement? Answer in a comment.
Answer : The curly braces are used to group the code that will be executed if the condition is true.
- Change the values of the variables so that neither message about cats is printed.
Answer : Change the value of cats to 20.
22. How Old Are You? - Link
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.
import java.util.Scanner;
public class HowOldAreYou
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
String name;
int age;
System.out.print( "Hey, what's your name? " );
name = keyboard.nextLine();
System.out.printf( "\nOk, %s, how old are you? ", name );
age = keyboard.nextInt();
if ( age < 16 )
{
System.out.printf( "\nYou can't drive, %s.", name );
}
if ( age < 18 )
{
System.out.printf( "\nYou can't vote, %s.", name );
}
if ( age < 25 )
{
System.out.printf( "\nYou can't rent a car, %s.", name );
}
if ( age >= 25 )
{
System.out.printf( "\nYou can do anything that's legal, %s.", name );
}
}
}
23. Else And If - Link
Type this one in and make it work, too.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." );
}
}
}
U:\My Documents\CompSci\>java ElseAndIf
We should take the cars.
Maybe we could take the buses.
All right, let's just take the buses.
U:\My Documents\CompSci\>
Assignments turned in without these things will receive half credit or less.In this section, you’re going to try to guess what you think the if statement is and what it does.
- What do you think else if and else are doing? Answer in a comment.
Answer : else if is used to check another condition if the previous condition is false. else is used to execute the code if all the conditions are false.
- Remove the else part at the beginning of one of the else if statements. What difference does that make? Why? Answer in a comment.
Answer : If the else part is removed, the code will check all the conditions even if one of the conditions is true. The else part is used to execute the code if the previous condition is false.
24. Weekday Name - Link
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:| Number | Day of week |
|---|
| 1 | Sunday |
| 2 | Monday |
| 3 | Tuesday |
| 4 | Wednesday |
| 5 | Thursday |
| 6 | Friday |
| 7 | Saturday |
| 0 | Saturday |
| anything else | "error" |
import java.util.Scanner;
public class WeekdayName
{
public static String weekday_name( int weekday )
{
String result = "";
if ( weekday == 1 )
{
result = "Sunday";
}
else if ( weekday == 2 )
{
result = "Monday";
}
else if ( weekday == 3 )
{
result = "Tuesday";
}
else if ( weekday == 4 )
{
result = "Wednesday";
}
else if ( weekday == 5 )
{
result = "Thursday";
}
else if ( weekday == 6 )
{
result = "Friday";
}
else if ( weekday == 7 || weekday == 0 )
{
result = "Saturday";
}
else
{
result = "error";
}
return result;
}
public static void main( String[] args )
{
System.out.println( "Weekday 1: " + weekday_name(1) );
System.out.println( "Weekday 2: " + weekday_name(2) );
System.out.println( "Weekday 3: " + weekday_name(3) );
System.out.println( "Weekday 4: " + weekday_name(4) );
System.out.println( "Weekday 5: " + weekday_name(5) );
System.out.println( "Weekday 6: " + weekday_name(6) );
System.out.println( "Weekday 7: " + weekday_name(7) );
System.out.println( "Weekday 0: " + weekday_name(0) );
System.out.println();
System.out.println( "Weekday 43: " + weekday_name(43) );
System.out.println( "Weekday 17: " + weekday_name(17) );
System.out.println( "Weekday -1: " + weekday_name(-1) );
GregorianCalendar cal = new GregorianCalendar();
int dow = cal.get(GregorianCalendar.DAY_OF_WEEK);
System.out.println( "\nToday is a " + weekday_name(dow) + "!" );
}
}
U:\My Documents\CompSci\>java WeekdayName
Weekday 1: Sunday
Weekday 2: Monday
Weekday 3: Tuesday
Weekday 4: Wednesday
Weekday 5: Thursday
Weekday 6: Friday
Weekday 7: Saturday
Weekday 0: Saturday
Weekday 43: error
Weekday 17: error
Weekday -1: error
Today is a Wednesday!
U:\My Documents\CompSci\>
25. How Old Are You, Specifically? - Link
Using if statements, else if, and else statements, make a program which displays a different message depending on the age given.| Age | Message |
|---|
| 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. import java.util.Scanner;
public class HowOldAreYou2
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
String name;
int age;
System.out.print( "Hey, what's your name? (Sorry, I keep forgetting.) " );
name = keyboard.nextLine();
System.out.printf( "\nOk, %s, how old are you? ", name );
age = keyboard.nextInt();
if ( age < 16 )
{
System.out.printf( "\nYou can't drive, %s.", name );
}
else if ( age < 18 )
{
System.out.printf( "\nYou can drive but you can't vote, %s.", name );
}
else if ( age < 25 )
{
System.out.printf( "\nYou can vote but you can't rent a car, %s.", name );
}
else
{
System.out.printf( "\nYou can do pretty much anything, %s.", name );
}
}
}
U:\My Documents\CompSci\>java HowOldAreYou2
Hey, what's your name? (Sorry, I keep forgetting.) Muqoffin
Ok, Muqoffin, how old are you? 21
You can vote but you can't rent a car, Muqoffin.
26. Space Boxing - Link
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:| # | Planet | Relative gravity |
|---|
| 1 | Venus | 0.78 |
| 2 | Mars | 0.39 |
| 3 | Jupiter | 2.65 |
| 4 | Saturn | 1.17 |
| 5 | Uranus | 1.05 |
| 6 | Neptune | 1.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.
import java.util.Scanner;
public class SpaceBoxing
{
public static Double planets_calc( int planet, double weight )
{
Double result;
if ( planet == 1)
{
result = weight * 0.78;
}
else if ( planet == 2)
{
result = weight * 0.39;
}
else if ( planet == 3)
{
result = weight * 2.65;
}
else if ( planet == 4)
{
result = weight * 1.17;
}
else if ( planet == 5)
{
result = weight * 1.05;
}
else
{
result = weight * 1.23;
}
return result;
}
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
double weight;
int planet;
System.out.print( "Please enter your current earth weight: " );
weight = keyboard.nextDouble();
System.out.println( "\nI have information for the following planets:" );
System.out.println( "\t1. Venus 2. Mars 3. Jupiter" );
System.out.println( "\t4. Saturn 5. Uranus 6. Neptune" );
System.out.print( "\nWhich planet are you visiting? " );
planet = keyboard.nextInt();
System.out.printf( "\nYour weight would be %.2f pounds on that planet.", planets_calc(planet, weight) );
}
}
27. ALittleQuiz - Link
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!
import java.util.Scanner;
public class LittleQuiz
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
int score = 0;
System.out.print( "Are you ready for a quiz? " );
if ( keyboard.next().toLowerCase().equals("n") )
{
System.out.println( "Okay, here it comes!" );
System.out.println( "\nQ1) What is the capital of Alaska?" );
System.out.println( "\t1) Melbourne" );
System.out.println( "\t2) Anchorage" );
System.out.println( "\t3) Juneau" );
System.out.print( "\n> " );
if ( keyboard.nextInt() == 3 ) {
System.out.println( "That's right!" );
score++;
} else {
System.out.println( "Sorry, \"Juneau\" is the capital of Alaska." );
}
System.out.println( "\nQ2) Can you store the value \"cat\" in a variable of type int?" );
System.out.println( "\t1) yes" );
System.out.println( "\t2) no" );
System.out.print( "\n> " );
if ( keyboard.nextInt() == 2 ) {
System.out.println( "That's correct!" );
score++;
} else {
System.out.println( "Sorry, \"cat\" is a string. ints can only store numbers." );
}
System.out.println( "\nQ3) What is the result of 9+6/3?" );
System.out.println( "\t1) 5" );
System.out.println( "\t2) 11" );
System.out.println( "\t3) 15/3" );
System.out.print( "\n> " );
if ( keyboard.nextInt() == 2 ) {
System.out.println( "That's correct!" );
score++;
} else {
System.out.println( "Sorry, the result of 9+6/3 is 11." );
}
System.out.printf( "\nOverall, you got %d out of 3 correct.\nThanks for playing!", score );
}
}
}
28. Modulus Animation - Link
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.) Assignments turned in without these things will not receive any points.
- Add several
if statements in ModulusAnimation.java so that it draws a little animation of your choosing. You must have a minimum of eight (8) different frames of animation, and it must loop smoothly.
Answer :
public class ModulusAnimation
{
public static void main( String[] args ) throws Exception
{
for ( int i=0; i<80; i++ )
{
if ( i%10 == 0 )
System.out.print(" M \r");
if ( i%10 == 1 )
System.out.print(" MU \r");
if ( i%10 == 2 )
System.out.print(" MUQ \r");
if ( i%10 == 3 )
System.out.print(" MUQO \r");
if ( i%10 == 4 )
System.out.print(" MUQOF \r");
if ( i%10 == 5 )
System.out.print(" MUQOFF \r");
if ( i%10 == 6 )
System.out.print(" MUQOFFI \r");
if ( i%10 == 7 )
System.out.print(" MUQOFFIN \r");
if ( i%10 == 8 )
System.out.print(" MUQOFFI \r");
if ( i%10 == 9 )
System.out.print(" MUQOFF \r");
if ( i%10 == 10 )
System.out.print(" MUQOF \r");
if ( i%10 == 11 )
System.out.print(" MUQO \r");
if ( i%10 == 12)
System.out.print(" MUQ \r");
if ( i%10 == 13)
System.out.print(" MU \r");
if ( i%10 == 14)
System.out.print(" M \r");
Thread.sleep(200);
}
}
}
32. Twenty Questions… well, actually just Two - Link
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 \ type | animal | vegetable | mineral |
|---|
| smaller than a breadbox | squirrel | carrot | paper clip |
| bigger than a breadbox | moose | watermelon | camaro |
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.
import java.util.Scanner;
public class TwentyQuestions
{
public static void main( String[] args )
{
Scanner input = new Scanner(System.in);
String question1, question2, answer = "";
System.out.println("TWO QUESTIONS!");
System.out.println("Think of an object, and I'll try to guess it.");
System.out.println("Question 1) Is it animal, vegetable, or mineral?");
System.out.print("> ");
question1 = input.nextLine();
System.out.println("Question 2) Is it bigger than a breadbox?");
System.out.print("> ");
question2 = input.nextLine();
if(question1.equalsIgnoreCase("animal") && question2.equalsIgnoreCase("yes")){
answer = "moose";
} else if(question1.equalsIgnoreCase("animal") && question2.equalsIgnoreCase("no")){
answer = "squirrel";
} else if(question1.equalsIgnoreCase("vegetable") && question2.equalsIgnoreCase("yes")){
answer = "carrot";
} else if(question1.equalsIgnoreCase("vegetable") && question2.equalsIgnoreCase("no")){
answer = "watermelon";
} else if(question1.equalsIgnoreCase("mineral") && question2.equalsIgnoreCase("yes")){
answer = "paper clip";
} else if(question1.equalsIgnoreCase("mineral") && question2.equalsIgnoreCase("no")){
answer = "camaro";
}
System.out.printf("My guess is that you are thinking of a %s.", answer);
System.out.println("\nI would ask you if I'm right, but I don't acctually care.");
}
}
33. Choose Your Own Adventure! - Link
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.
import java.util.Scanner;
import java.io.*;
public class Adventure1 {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int score = 0;
String answer;
System.out.println("WELCOME TO MATH ADVENTURE!\n");
System.out.println("1 + 1?");
System.out.print("> ");
answer = input.nextLine();
if (answer.equals("2")){
score += 1;
System.out.println("1 x 2?");
System.out.print("> ");
answer = input.nextLine();
if (answer.equalsIgnoreCase("2")){
score += 1;
System.out.println("1 x 3?");
System.out.print("> ");
answer = input.nextLine();
if (answer.equalsIgnoreCase("3")){
score += 1;
System.out.println("ANDA BERHASIL MENYELESAIKAN TANTANGAN!");
System.out.println("Score anda " +score);
} else {
System.out.println("ANDA HANYA MENYELESAIKAN BEBERAPA TANTANGAN!");
System.out.println("Score anda " +score);
}
} else {
System.out.println("1 + 1?");
System.out.print("> ");
answer = input.nextLine();
if (answer.equalsIgnoreCase("2")){
score += 1;
System.out.println("ANDA HANYA MENYELESAIKAN BEBERAPA TANTANGAN!");
System.out.println("Score anda " +score);
} else {
System.out.println("ANDA HANYA MENYELESAIKAN BEBERAPA TANTANGAN!");
System.out.println("Score anda " +score);
}
}
} else {
System.out.println("1 + 2?");
System.out.print("> ");
answer = input.nextLine();
if (answer.equalsIgnoreCase("3")){
score += 1;
System.out.println("1 x 3?");
System.out.print("> ");
answer = input.nextLine();
if (answer.equalsIgnoreCase("3")){
score += 1;
System.out.println("ANDA HANYA MENYELESAIKAN BEBERAPA TANTANGAN!");
System.out.println("Score anda " +score);
} else {
System.out.println("ANDA HANYA MENYELESAIKAN BEBERAPA TANTANGAN!");
System.out.println("Score anda " +score);
}
} else {
System.out.println("1 + 1?");
System.out.print("> ");
answer = input.nextLine();
if (answer.equalsIgnoreCase("2")){
score += 1;
System.out.println("ANDA HANYA MENYELESAIKAN BEBERAPA TANTANGAN!");
System.out.println("Score anda " +score);
} else {
System.out.println("ANDA GAGAL MENYELESAIKAN TANTANGAN!");
System.out.println("Score anda " +score);
}
}
}
}
}
34. Age Messages 3 - Link
Using if statements with compound conditions (like &&), make a program that displays a single message depending on the age given.| Age | Message |
|---|
| 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. import java.util.Scanner;
public class AgeMessages3
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
String name;
int age;
System.out.print( "Your name: " );
name = keyboard.next();
System.out.print( "Your age: " );
age = keyboard.nextInt();
if ( age > 0 && age < 16 )
{
System.out.printf( "\nYou can't drive, %s.", name );
}
if ( age >= 16 && age <= 17 )
{
System.out.printf( "\nYou can drive but you can't vote, %s.", name );
}
if ( age >= 18 && age <= 24 )
{
System.out.printf( "\nYou can vote but you can't rent a car, %s.", name );
}
if ( age >= 25 )
{
System.out.printf( "\nYou can do pretty much anything, %s.", name );
}
}
}
35. Two More Questions - Link
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. | inside | outside | both |
|---|
| alive | houseplant | bison | dog |
| not alive | shower curtain | billboard | cell 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!
import java.util.Scanner;
public class TwoMoreQuestions
{
public static void main( String[] args )
{
Scanner input = new Scanner(System.in);
String question1, question2, answer = "";
System.out.println("TWO MORE QUESTIONS, BABY!");
System.out.println("\nThink of something and I'll try to guess it!");
System.out.print("\nQuestion 1) Does it belong inside or outside or both?");
question1 = input.nextLine();
System.out.print("Question 2) Is it alive?");
question2 = input.nextLine();
if(question1.equalsIgnoreCase("inside") && question2.equalsIgnoreCase("yes")){
answer = "houseplant";
}
if(question1.equalsIgnoreCase("inside") && question2.equalsIgnoreCase("no")){
answer = "shower curtain";
}
if(question1.equalsIgnoreCase("outside") && question2.equalsIgnoreCase("yes")){
answer = "bison";
}
if(question1.equalsIgnoreCase("outside") && question2.equalsIgnoreCase("no")){
answer = "billboard";
}
if(question1.equalsIgnoreCase("both") && question2.equalsIgnoreCase("yes")){
answer = "dog";
}
if(question1.equalsIgnoreCase("both") && question2.equalsIgnoreCase("no")){
answer = "cell phone";
}
System.out.printf("\nThen what else could you be thinking of besides a %s?!?", answer);
}
}
36. BMI Categories - Link
(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.| BMI | Category |
|---|
| less than 18.5 | underweight |
| 18.5 to 24.9 | normal weight |
| 25.0 to 29.9 | overweight |
| 30.0 or more | obese |
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
Answer Sample Output 1:import java.util.Scanner;
public class BMICategories
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
double m, kg, bmi;
String category = "";
System.out.print( "Your height in m: " );
m = keyboard.nextDouble();
System.out.print( "Your weight in kg: " );
kg = keyboard.nextDouble();
bmi = kg / Math.pow(m, 2);
if ( bmi < 18.5 )
{
category = "underweight";
}
if ( bmi >= 18.5 && bmi <= 24.9 )
{
category = "normal weight";
}
if ( bmi >= 25.0 && bmi <= 29.9 )
{
category = "overweight";
}
if ( bmi >= 30.0 )
{
category = "obese";
}
System.out.printf("\nYour BMI is %.8s", bmi);
System.out.printf("\nBMI Category: %s", category);
}
}
Answer Sample Output 2:import java.util.Scanner;
public class BMICategories
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
double inches, pounds, bmi;
String category = "";
System.out.print( "Your height in inches: " );
inches = keyboard.nextDouble();
System.out.print( "Your weight in pounds: " );
pounds = keyboard.nextDouble();
bmi = (pounds / Math.pow(inches, 2)) * 703;
if ( bmi < 18.5 )
{
category = "underweight";
}
if ( bmi >= 18.5 && bmi <= 24.9 )
{
category = "normal weight";
}
if ( bmi >= 25.0 && bmi <= 29.9 )
{
category = "overweight";
}
if ( bmi >= 30.0 )
{
category = "obese";
}
System.out.printf("\nYour BMI is %.4s", bmi);
System.out.printf("\nBMI Category: %s", category);
}
}
For +10 bonus points, use more if statements to show the ALL the BMI categories.| BMI | Category |
|---|
| less than 15.0 | very severely underweight |
| 15.0 to 16.0 | severely underweight |
| 16.0 to 18.5 | underweight |
| 18.5 to 25.0 | normal weight |
| 25.0 to 30.0 | overweight |
| 30.0 to 35.0 | moderately obese |
| 35.0 to 40.0 | severely obese |
| 40.0 or more | very severely (or “morbidly”) obese |
| Sample Output: | |
Your height in inches: 70
Your weight in pounds: 90
Your BMI is 12.9
BMI Category: very severely underweight
Answer :
import java.util.Scanner;
public class BMICategories
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
double inches, pounds, bmi;
String category = "";
System.out.print( "Your height in inches: " );
inches = keyboard.nextDouble();
System.out.print( "Your weight in pounds: " );
pounds = keyboard.nextDouble();
bmi = (pounds / Math.pow(inches, 2)) * 703;
if ( bmi < 15.0 )
{
category = "very severely underweight";
}
if ( bmi >= 15.0 && bmi <= 16.0 )
{
category = "severely underweight";
}
if ( bmi >= 16.0 && bmi <= 18.5 )
{
category = "underweight";
}
if ( bmi >= 18.5 && bmi <= 25.0 )
{
category = "normal weight";
}
if ( bmi >= 25.0 && bmi <= 30.0 )
{
category = "overweight";
}
if ( bmi >= 30.0 && bmi <= 35.0 )
{
category = "moderately obese";
}
if ( bmi >= 35.0 && bmi <= 40.0 )
{
category = "severely obese";
}
if ( bmi >= 40.0 )
{
category = "very severely (or \"morbidly\") obese";
}
System.out.printf("\nYour BMI is %.4s", bmi);
System.out.printf("\nBMI Category: %s", category);
}
}
37. Gender Game - Link
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.
import java.util.Scanner;
public class GenderGame
{
public static void main( String[] args )
{
Scanner input = new Scanner(System.in);
int age;
String gender, firstName, lastName, married, call;
System.out.print( "What is your gender (M or F): " );
gender = input.nextLine();
System.out.print( "First name: " );
firstName = input.nextLine();
System.out.print( "Last name: " );
lastName = input.nextLine();
System.out.print( "Age: " );
age = input.nextInt();
if (gender.equalsIgnoreCase("F") && age >= 20){
System.out.printf("Are you married, %s (y or n)? ", firstName);
input.nextLine();
married = input.nextLine();
if(married.equalsIgnoreCase("y")){
call = "Mrs " + lastName;
} else {
call = "Ms " + lastName;
}
} else if (gender.equalsIgnoreCase("M") && age >= 20){
call = "Mr. " + lastName;
} else {
call = firstName + " " + lastName;
}
System.out.printf("\nThen I shall call you %s.", call);
}
}
38. compareTo() Challenge - Link
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: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
public class CompareToChallenge
{
public static void main( String[] args )
{
System.out.println( "5 Produces less than 0:" );
System.out.print( "Comparing \"axe\" with \"dog\" produces " );
System.out.println( "axe".compareTo("dog") ); // -3
System.out.print( "Comparing \"apple\" with \"banana\" produces " );
System.out.println( "apple".compareTo("banana") ); // -1
System.out.print( "Comparing \"apple\" with \"dog\" produces " );
System.out.println( "apple".compareTo("dog") ); // -3
System.out.print( "Comparing \"apple\" with \"elephant\" produces " );
System.out.println( "apple".compareTo("elephant") ); // -4
System.out.print( "Comparing \"apple\" with \"zebra\" produces " );
System.out.println( "apple".compareTo("zebra") ); // -25
System.out.println( "\n5 Produces greater than 0:" );
System.out.print( "Comparing \"dog\" with \"axe\" produces " );
System.out.println( "dog".compareTo("axe") ); // 3
System.out.print( "Comparing \"banana\" with \"apple\" produces " );
System.out.println( "banana".compareTo("apple") ); // 1
System.out.print( "Comparing \"dog\" with \"apple\" produces " );
System.out.println( "dog".compareTo("apple") ); // 3
System.out.print( "Comparing \"elephant\" with \"apple\" produces " );
System.out.println( "elephant".compareTo("apple") ); // 4
System.out.print( "Comparing \"zebra\" with \"apple\" produces " );
System.out.println( "zebra".compareTo("apple") ); // 25
System.out.println( "\n2 Produces 0:" );
System.out.print( "Comparing \"apple\" with \"apple\" produces " );
System.out.println( "apple".compareTo("apple") ); // 0
System.out.print( "Comparing \"applebee's\" with \"applebee's\" produces " );
System.out.println( "applebee's".compareTo("applebee's") ); // 0
}
}
U:\My Documents\CompSci\>java CompareToChallenge
5 Produces less than 0:
Comparing "axe" with "dog" produces -3
Comparing "apple" with "banana" produces -1
Comparing "apple" with "dog" produces -3
Comparing "apple" with "elephant" produces -4
Comparing "apple" with "zebra" produces -25
5 Produces greater than 0:
Comparing "dog" with "axe" produces 3
Comparing "banana" with "apple" produces 1
Comparing "dog" with "apple" produces 3
Comparing "elephant" with "apple" produces 4
Comparing "zebra" with "apple" produces 25
2 Produces 0:
Comparing "apple" with "apple" produces 0
Comparing "applebee's" with "applebee's" produces 0
39. Alphabetical Order - Link
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".
import java.util.Scanner;
public class AlphabeticalOrder
{
public static void main( String[] args )
{
Scanner input = new Scanner(System.in);
String lastName;
System.out.print( "What's your last name? " );
lastName = input.nextLine();
if (lastName.compareTo("Carswell") <= 0){
System.out.printf("You don't have to wait long, %s.", lastName);
} else if (lastName.compareTo("Jones") <= 0){
System.out.printf("That's not bad, %s.", lastName);
} else if (lastName.compareTo("Smith") <= 0){
System.out.printf("Looks like a bit of a wait, %s.", lastName);
} else if (lastName.compareTo("Young") <= 0){
System.out.printf("It's gonna be a while, %s.", lastName);
} else {
System.out.printf("Not going anywhere for a while?, %s.", lastName);
}
}
}
U:\My Documents\CompSci\>java AlphabeticalOrder
What's your last name? nuha
You don't have to wait long, nuha.
40. The Worst Number-Guessing Game Ever - Link
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....
import java.util.Scanner;
public class WorstGuessing
{
public static void main( String[] args )
{
Scanner input = new Scanner(System.in);
int secretNumber = 4, guess;
System.out.println("TEH WORST NUBMER GESSING GAME EVAR!!!!!!!1!");
System.out.println("\nI'M THKING OF A NBR FROM 1-10. TRY 2 GESS!");
System.out.print("Your guess: ");
guess = input.nextInt();
if (guess == secretNumber){
System.out.println("LOL!!! U GOT IT! I CANT BELEIVE U GESSED IT WAS " + secretNumber + "!");
} else {
System.out.println("W00T! U SUX0R!!! I PWN J00!!! IT WAS " + secretNumber + "!");
}
}
}
U:\My Documents\CompSci\>java WorstGuessing
TEH WORST NUBMER GESSING GAME EVAR!!!!!!!1!
I'M THKING OF A NBR FROM 1-10. TRY 2 GESS! 5
W00T! U SUX0R!!! I PWN J00!!! IT WAS 4!