After working through the introductory videos with what programs
to use (already had Notepad++, which I absolutely love for it’s color coding),
I finally started getting into creating some small programs.
Here’s the final code from the video
class apples {
public static void main(String args[]){
int age = 45;
if (age >= 60)
System.out.println("You are a senior citizen");
else if (age >=50)
System.out.println("You are in your 50's");
else if (age >=40)
System.out.println("You are in your 40's");
else
System.out.println("You are a young buck");
}
}
This is where I asked
why the age was set as a static variable if you’re going to teach the idea
behind else/if – at this point we've already learned how to import Scanner, input
text from the keyboard and store it as a variable, why not make this small
piece of code do exactly that?
import java.util.Scanner;
class apples {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int age = 45;
if (age >= 60)
System.out.println("You are a senior citizen");
else if (age >=50)
System.out.println("You are in your 50's");
else if (age >=40)
System.out.println("You are in your 40's");
else
System.out.println("You are a young buck");
}
}
Now that we can input
text we need to set the variable of age to be an empty integer and assign it be
whatever is input to the program
import java.util.Scanner;
class apples {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int age;
age = input.nextInt();
if (age >= 60)
System.out.println("You are a senior citizen");
else if (age >=50)
System.out.println("You are in your 50's");
else if (age >=40)
System.out.println("You are in your 40's");
else
System.out.println("You are a young buck");
}
}
Then Lastly let’s give
the user a message that tells them what to do when the program starts.
import java.util.Scanner;
class apples {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int age;
System.out.println("Enter your age: ");
age = input.nextInt();
if (age >= 60)
System.out.println("You are a senior citizen");
else if (age >=50)
System.out.println("You are in your 50's");
else if (age >=40)
System.out.println("You are in your 40's");
else
System.out.println("You are a young buck");
}
}
Now when the program is
run it first asks you what your age is and allows you to input it. Based on
what you put it the else/if statement will respond accordingly.
No comments:
Post a Comment