Core Theme: This video series teaches Java programming fundamentals, starting with setting up the development environment (JDK and IDE) and progressing through basic syntax, variables, control flow (if/else, switches), loops (while, for), methods, arrays, strings, exception handling, file I/O, and object-oriented programming concepts like inheritance, polymorphism, and encapsulation. It culminates in building practical projects like a calculator, a number guessing game, a shopping cart, a compound interest calculator, a weight converter, a simple banking application, a dice rolling game, a slot machine, a countdown timer, an alarm clock with music, and a basic Hangman game.
Key Points:
Environment Setup: Essential tools like JDK and IDE (IntelliJ) are covered for starting Java development.
Mind Map
คลิกเพื่อขยาย
คลิกเพื่อสำรวจ Mind Map แบบอินเตอร์แอคทีฟฉบับเต็ม
hey how's it going everybody in this
video I'm going to teach you everything
you need to know to start coding with
Java this series even contains about 15
Hands-On projects that we're going to
code together our final project will be
a functioning alarm clock that plays
music of your choice if you've never
coded anything in your life don't worry
we're going to start from the very
beginning I encourage you to sit back
show I don't like boring introductions
so we're just going to Jump Right In to
start coding with Java you'll need two
things a Java development kit also known
as a jdk a jdk contains a compiler a
compiler will compile your source code
your written code into bite code which
can run on a machine you'll also need an
integrated development environment IDE
an IDE is a fancy term for a workspace
in which we can write code because
sometimes notepad just doesn't cut it
we'll get started by downloading a jdk a
Java development kit okay here's how to
download the jdk the Java development
kit you can easily just Google or do a
search for jdk download we're going to
use the one by Oracle so we'll click on
this link I'll also post the link in the
description of this video if you would
like to access it that way we will
download the latest jdk version as of
the filming of this video we're on jdk
23 we're going to look for our operating
system I'm running Windows I will
download the 64- bit installer by
clicking this
download the download is complete we're
going to open this
next our jdk has been successfully
installed we can close it and that's all
we got to do for the
jdk now we need to install an IDE an
integrated development
environment one I recommend is intellig
you can easily just Google or do a
search for intellig
download we'll select the top
link now if you're not brought to this
page let's say you're at a different
page go to the top right where it says
get intellig click it and you should be
brought to a download page this version
is a 30-day trial but if you scroll down
there is a free version this is the
Community Edition because I don't like
to pay for things select the correct
download for your operating system I'm
executable once the download is complete
we will open this executable for
intellig select
next choose a destination folder I'll
keep it as is Click
next you can create a desktop shortcut I
now this is important too you can update
the path variable it basically tells
your operating system where to find the
executable files this is useful if
you're going to be running Java code
from command prompt or terminal but we
won't be doing that in this series you
can always come back later and update
install all right and we can finish we
might as well start intellig right away
I'm going to check this check boox to
run intellig and
finish we should now be at a welcome
screen for intellig we need to create a
project select new project I'll name my
project my first
project select the latest version of
your jdk I have jdk version 23 there is
a checkbox and it's most likely going to
be checked that says add sample code
just as a beginner I recommend
unchecking this it'll autogenerate some
sample code for us but we're going to do
that ourselves I'll show you how and then
then
create within our project folder
navigate to your Source folder it has a
name of
SRC we need to create a main Java file
go to the top toolbar go to file new
Java class we'll name this class main
it's going to contain the main body of
our code then select class
now the font is probably going to be really
really
small here's how to change
that go to the top toolbar go to
settings go to editor
editor
General and you can check this checkbox
for change font size with Control Plus
Mouse wheel apply okay now you should be
able to zoom in if you hold control and
scroll your mouse wheel now we can
actually read something in Java in order
to get some code to run you need a main
method within our class of main there's
a set of curly braces we'll type the
following public static void main add a
set of parentheses then a set of curly
braces within the set of parentheses
you're going to type the following
string straight brackets
args like you're a pirate
you need this method in order for your
program to run over the course of this
series we'll learn what each of these
keywords means but as a beginner think
of it as a magic spell that you have to
say in order to get your program to run
to run your program you're going to
click the screen Arrow or you can hold
F10 if we have written the main method
successfully we should have no
errors it says processed finished with
exit code zero that means everything is
running fine if I were to delete this
main method we can't actually run the
program so be sure that that method is
in to Output some text to the console
window we're going to type system with a
capital s. out. print add a set of
parentheses then a
semicolon in Java you'll end most of
your statements with a semicolon it's
kind of like a period at the end of a
sentence in the English language
within the set of parentheses we'll add
a set of double quotes whatever we would
like to Output we're going to type
within the set of double quotes think of
a food you like I'll type I like
pizza and then we can run this and this
should be the
output again I'm going to go to the
Green Arrow or you can hold shift
F10 and a console window should pop up
that says I like pizza or whatever your
here let's add another line of
system.out.print end it with the
semicolon within quotes which we type I
like pizza it's really
good let's run it
again all right here's our output I like
pizza it's really good
now these are both on the same line to
move your output down to the next line
you can use print Ln meaning print
line now it should look something like
good if you type back sln that's an
escape sequence for a new line and that
works too besides print line I like
pizza it's really good
let's add another line of text
system.out.print or print
line I like pizza it's really good buy me
me
character I like pizza it's really good
buy me
pizza or again you could use print
thing now you can write a comment
comments aren't displayed as output to
write a comment you use two forward
slashes and the text should be gray out
comments are good as notes for yourself
or for other developers let's add a
comment that this is my first Java
program when we run this this won't
display us out output it's really just
used as notes we still have our output
it hasn't
changed you can even add a multi-line
comment with a forward slash then an
asterisk to end a multi-line comment you
need an asterisk then a forward slash
I'll write this is a
multi- line
comment this won't output either
we don't see either of these
comments this is specific for intellig
but you can change the console font and
the colors I kind of find this hard to
read to do that we're going to go to the
top menu under file go to
settings under color scheme go to
console font here you can change the
font if you would like or the colors
I'll change the colors I'll make the
output bright green so it's easier to
read I'll go to console
standard output and select a new color
I'll select something
green apply and I think that looks
pretty good it's more readable that way
I'll also change the system output
too I'll make it kind of gray out that's pretty
pretty
good yeah and there's our output I like
pizza it's really good buy me
pizza now a shortcut to type system. out
at print line if you're using intellig
is to type s o u t then hit tab that's
going to autogenerate a print line
statement for you I didn't realize this
trick until a little bit later so you
don't always need to type out this
statement you can just autogenerate it
all right everybody and that is your
first Java program your homework in the
comment section is to post three print
line statements maybe type A poem or
some song lyrics or something and well
everybody that is your first Java program
all right everybody so we are moving on
to variables in Java probably back in
elementary school or middle school you
learned about variables in algebra a
variable was a representation of a
number well in programming we have
variables too a variable is a reusable
container for a value a variable behaves
as if it was the value it contains but
variables can contain more than just
numbers they can contain characters and
even entire words there's different data
types a whole number would be an integer
a number that includes a decimal would
be a double there's two categories of
variables we'll discuss primitive and
reference primitive variables are simple
values like numbers they're stored
directly in memory usually in a location
known as the stack reference variables
actually hold memory addresses on the
stack they point to a location in a
different area known as the Heap think
of it this way if I give you a primitive
variable that would be the same as me
handing you
$10 but if I give you a reference
variable a memory address that would be
the same as me giving you an IOU that
says I owe you $10 but the actual money
I owe you is at the bank that might be a
beginner's way of thinking of the
difference between a primitive and
reference data type primitive I'm giving
you $10 a reference data type I'm giving
you an IOU that I owe you $10 we'll
discuss the different data types we'll
begin with integers an INT short for
integer is a primitive data type I'll
show you how we can create an integer
variable in Java there's two steps to
creating a variable the first is
declaration the second is assignment
let's say we would like to create a
variable that stores a whole number an
integer with the first step of
Declaration we're going to first type
the data type of what we would like to
store exactly so for integers we will
type int then we should think of a
unique variable name we don't want to
say X or something similar that would
make sense in basic algebra but in
programming you want your variables to
be descriptive like shut up in
programming you want your variables to
be descriptive so let's say we are
working with let's say in age end this
line with a semicolon so this is
declaration step one we are creating a
variable named age if I was to print my
variable of age system.out.print
system.out.print
is variable age might not have been
initialized we're using a variable but
we've never given it a value we've never
completed step two of
assignment so we can set age equal to a
value so on my YouTube channel the
average age of my viewers is
approximately 21 or so so let's set age
to be 21 and then we'll print
it so that outputs 21 if I were to
change this to
30 then my variable age would behave as
if it was the number 30 so those are
integers they're whole numbers let's say
that I'm
30.5 let's see what happens exactly you
can see that intellig is already giving
us a warning that we're working with a
different data type known as doubles so
if I were to run this we get an error
message we have incompatible types from
double to in if we declare a variable as
an integer they can only store whole
integers let's think of a few more
examples another example of an integer
could be a year so let's say the year is 2025
2025
then we'll print our year
year
2025 or maybe a quantity int
quantity equals
1 then we'll print our
quantity one so in working with
quantities they're whole numbers usually
right we wouldn't have let's say half a
product 1.5 I would like 1.5 Nintendo
switches that wouldn't make sense right
they would would be whole numbers like
two now you can output a variable with a
string of text as
well let's say the year
is then I'll add plus a variable year
make sure that the variable is not within
within
quotes So currently this says the year is
is
2025 you do have to pay attention to the
spacing so after the word is I'm going
to add a space to separate is and the variable
variable
year the year is
2025 now if our variable was within
quotes we would literally be printing
the word year the year is year so don't
do that unless it's
intentional let's go on to the next data
type the next data type is double double
is a number but it can contain a decimal
portion unlike int ins are whole
numbers so this time we will create a
variable type of double what are some
examples of a variable that could be a
double let's say a price there could be
$19.99 or perhaps a GPA a grade point
3.5 or a temperature
double temperature equals
12.5 all right let's output some of
these let's do Price
Price system.out.print
system.out.print
price
19.99 let's add a unit of currency I'll
so Dollar Sign Plus price
$19.99 if you were to assign a variable
that's a double data type but store an
integer here's what would
happen we would just add 0 Z to the end
it's still a double so those are doubles
they're numbers that can contain a
decimal portion unlike
integers okay then the next data type we
have is charart
meaning character Char pronounced like
the word
Charizard so with chars what are a few
examples of single characters we could
use let's say a grade like a letter
grade with chars characters we enclose
them within single quotes let's say we
have the letter A that's the grade we
got on the last test or
maybe I'll put an exclamation point or
something or currency Char currency
equals pick a unit of currency I'll pick
dollars okay then let's output some of these
these system.out.print
system.out.print
grade which is an
A or our symbol
an exclamation point or our
currency which is American
dollars so then we have something called
booleans booleans are either true or
false we will declare this variable as a
Boolean let's check to see if somebody
is a student our variable name will be
is student and this equals true or false
so if I am a student I would say true
now a common naming convention in Java
is called camel case naming convention
if your variable name takes up two words
such as is and student when you combine
them the first letter of the first word
should be lowercase then any word after
the first letter is going to be
uppercase so is student and I will set
that to be true maybe something is for
sale or not Boolean for sale equals
false it's not for sale is somebody
online Boolean is online now I will set
that to be true these are a few examples
of Boolean
variables now you could output them
directly using system.out.print line
Let's test it system.out.print line
let's output is student
are we a student that is true is
something for sale for
sale that is false now with Boolean
variables we don't typically output them
directly to the console we tend to use
them more internally within a
program one place in which you might see
them is with the use of if statements
and this is a future topic we'll revisit
it later but I want to demonstrate the
usefulness of booleans so this is an if
statement we can check some condition
parenthesis then curly
braces if our condition is true if is
student double equals true but we could
simplify this
to if is student if this variable
contains true which it does we can
execute some code system.out.print
system.out.print
line we will print the following
you are a
student if this Boolean variable
contains true we will print the
following you are a
student or we could add else an else
Clause else let's
print you are not a
student So currently we're still a
student but if this Boolean variable
contained a value of false we would
perform form the else
statement you are not a student so we'll
cover if statements in a future topic
you don't necessarily need to know how
these work right now but that's one of
the uses of booleans they can only
contain true or
false these are a few of the basic
primitive data types for beginners int
for integers they contain whole numbers
doubles are numbers but they can contain
a decimal chars meaning characters are
single characters and booleans which are
either true or false these are a few of
the beginner primitive data types but
there's still a lot more than this
there's floats there's long doubles all
sorts of different data types but you
don't need to know those as a beginner I
would just stick to these four for now
so then we have the reference data types
A few of which include strings arrays
and objects in this topic we're only
going to discuss strings a series of
characters phas and objects are really
complex we'll revisit these later so
we're going to create a string a series of
of
characters so the data type is going to
be string an example of a series of
characters could be a name what's your
name with strings we enclose them within
double quotes chars single characters
are single quotes it's really easy to
mix the two up you might do it a few
times as a beginner so type in your name
in including a space I'll use my YouTube channel
channel
name and then we will output our name
name and your first and last name should
appear now we could use this variable of
name within another string this is known
as string
concatenation so let's say
say
hello plus our name
hello bro code or whatever your name is
what are a few other examples of strings
we could
write let's add string food
equals again within a set of double
quotes add your favorite food mine is
pizza then let's type again system.out.print
line your favorite food is
plus the variable
pizza what about an email string email
equals make up an email fake1 123@gmail.com
strings they can contain numbers but we
treat them more as characters rather
than actual numbers that we can use for
any sort of math or
arithmetic so let's print our email your email
email
or what about a
car string
car think of a car that you like I will
pick a Mustang that's another example of
a string or a color
string color equals
red so strings are a series of
characters they have a reference data
type you may have also noticed that the
font color of strings is different from
the primitive data types too of booleans
chars doubles and Ins at least within my
workspace the font color is orange and
with strings the font color of these
data types is white now we're going to
cover a few exercises
so let's start with our name
system.out.print line we will print
hello plus our name variable it's a
string hello your first and last
name let's print our age system.out.print
system.out.print
line u
r we're going to insert our variable age
then add another string another string
literal you are age years old again do
pay attention to the
spacing you are 30 years
old let's use my
GPA that's a
line your GPA
is then we will insert our GPA
your GPA is
grade system.out.print
line your average letter grade
is our variable
grade your average letter grade is is a
now within a single print line statement
we're going to combine multiple
variables let's say we're going to
Output our
color a
year and our
car all within one print statement system.out.print
system.out.print
line let's say we're choosing a car your
choice is a We'll add our color variable
plus the
year plus our car let's see what happens
exactly if we attempt
this so we've combined all three
variables red 2025 and our car of
Mustang so we're going to add some space
characters between each to separate them
so plus a space character add that after the
the
color after the
year we'll add a space between color and
year and year and
car so your choice is a red 2025
Mustang let's display the
price system.out.print
is plus currency
I picked American
price the price is
$9.99 uh for a car let's up that that's
way too cheap that's too good to be true
99 that's more
realistic now we're going to use this
Boolean variable of for
sale if
for sale if this is true then we're
print there is
is
a plus
Car Plus the text of for
sale else we will print something else
let's say
the plus Car Plus is not for sale for sale
sale
currently that's set to false the
true there is a Mustang for sale for
sale is set to true all right everybody
so those are variables in Java a
variable is a reusable container for a
value a variable behaves as if it was
the value that it contains there's two
different categories of variables
primitive and reference primitive data
types are simple values like integers
floats single characters and
booleans they're stored directly in
memory usually in a location known as
the stack reference variables such as
strings which are a series of characters
like your name or an email they're more
complicated we store a memory address
that points to a location in the Heap
and your homework assignment is in the
comment section post five variables a
string an integer a double A Char and a
Boolean and if you don't do your
homework you're going to make me sad and
well everybody that is an introduction
Java hello again friends so today I'm
going to show you how we can accept user
input in Java we will need the help of
what is called a scanner a scanner is an
object that allows us to accept user
input in Java however in order to use a
scanner we actually need to import it
from the certain package called
utilities or util at the top of our Java
file we're going to write the following
statement import Java do
util this is a package do scanner
scanner is a class so make sure you have
this import at the top before we get
started to sum up programming we
typically accept input process it then
produce output so that's why accepting
user input is important we would like to
do something with the input so to accept
user input we're going to create a
scanner object so type this scanner
that's the name of the class
class scanner that's going to be the
name of the object we'll be working with
do pay attention to the
capitalization our scanner object is all
lowercase characters whereas in the
first scanner has an uppercase
s scanner scanner equals new scanner add
a set of parenthesis then a semicolon
within the set of parentheses we're
going to type
system.in our scanner object can read
user input however it is good practice
if you create a scanner object at the
end of your program when you're done
we're going to take our scanner object
and use the close
method so scanner. close parenthesis
semicolon if you don't close your
scanner it can lead to unexpected
behavior for example let's say that we
read a file well after we're done
reading the file we'll want to close the
file when we open something we typically
want to close
it we're going to create a prompt within
our console that says enter your name
then a user will be able to type in
their name we'll need a user prompt to
work with so let's say system.out.print
name after receiving this prompt a user
is going to be able to type in their
name we're going to use our scanner
object scanner
next line parentheses semicolon so a
user is going to be able to type in a
string of text so let's type in our full
name then hit
enter however with this user input we're
not doing anything with it so let's
assign it to a
variable so with our line of scanner.
next line we will declare a variable and
assign it string name equals scanner.
nextline we have declaration and
assignment those two
steps and then once we have our name
let's output it system.out.print line
name so enter your name type in your
full name hit enter and the output
should be hello whatever your first and
last name is now if you prefer we can
put the input on the same line as the
prompt we're going to use print instead
of print Line Print line will add a new
line character to the
end so let's stick with
print so the input will be on the same
line as the prompt if you prefer it that
way so the next line method of our
scanner object it reads A String of
characters including any spaces if you
so if I were to type in my full name
with the first and last name separated
with the
space we only get the first name next
doesn't read any
spaces so use what you would prefer I
typically just use next
line to read an integer there's a
different method called Next int this
time let's create a prompt of enter your
age I'll use print instead of print line
we will assign a variable of age int age
equals use our scanner
object use the built-in next int
method then once we have our integer of
age let's output it system.out.print
line u
enter your name type in your name enter
your age oops I'm going to add a colon
and a space after my prompt just because
better okay enter your full
name enter your age hello your name you
are whatever your age is years old so
that's how to accept an integer if you
were to type in a floating point number
or a double anything that includes a
decimal now check this out our variable
of age should be an integer if we type
in something that contains a decimal
like a floating Point number or a double
let's say that I'm
25.9 well we get an error here it says
we have an error at line 12 where we
accept an integer so if you need a
double there's a next Double method of
scanners so this time let's ask for a
GPA what is your GPA your grade point
average we will assign a variable that's
going to be of the double data type
double GPA equals again use our
scanner use the next Double
method and then let's output
it system.out.print
line your GPA is plus our variable
GPA so again let's go through the
prompts type in your name type in your
age what is your GPA uh let's use print
Line enter your name enter your age what
is your GPA let's say my GPA is 2.1 I'm
just barely passing hey C get degrees
right your GPA is the GPA variable so
that's how to accept the double use the
next Double method of scanners now for
some reason if you need a Boolean
booleans are either true or false here's
how we can accept
that system.out.print line let's ask are
you a
student then I'll add a prompt for
true or false so the US user knows to
type in one of these instead of yes or
no so we will create a Boolean variable
of is student equals use our scanner
object use the next Boolean
method and then let's output
it system.out.print
line let's say student colon space plus
is student I think an if statement would
be better we'll cover that in a
moment again go through the prompts type
in your name type in your age type in a
GPA are you a student true or false
let's say that's true student
true and again I'm going to use print
instead of print
line not necessary but I think it looks
better let's use an if statement instead
when checking is student is true or not
so if is student again if statements
will be a future lesson we'll cover
pretty soon if is student if that's true
then we will
print let's print you are
enrolled as a
student else we will print something
else if that's not true if it's false you
are
okay enter your name enter your age
enter a GPA are you a student let's say
that it's
false okay we have our name our age our
GPA and then we're outputting you are
not enrolled you are not enrolled in
classes because we said
well then we get the output you are
enrolled as a student that's how to
accept user input of different data
types A few of which include strings
integers doubles and
booleans now there's one common issue
when accepting an integer or double than
demonstrate so we have our scanner
let's say we ask for a user's
age enter your
age and I'll make this a print statement
instead of print
line int age equals use our scanner use
the next int
method and then let's ask what the
user's favorite color is enter your favorite
favorite
color we will store that within a
variable named color and it's going to
be of the string data type string color
equals use our scanner object use the in
next line
method then we'll output the
following system.out.print line you are Plus
Plus
Age years
old as well
as you like the
color plus our variable color
happens enter your age 25 hit
enter enter your favorite color you are
25 years old you like the color so
what's going on here exactly so when we
type in a number for example 25 then hit
enter within the input buffer there's
still a new line character because we
hit enter
so the next line method is picking up
that new line character and using that
as the
input so we need to get rid of that new
line character this is a common problem
that you might see in Java if you accept
an integer or a double then accept a
string of text so one way in which we
can clear the input buffer to get rid of
that new line character is after
accepting an integer or a double we can
use our scanner and call the next line
method but don't assign it to anything
that should get rid of that new line
character in the input buffer if that
problem comes up so let's try this again
enter an age enter a color you are 25
years old you like the color red so if
you encounter that problem I would just
call the next line method of your
scanner object to clear the input buffer
now we're going to cover an
exercise in this exercise we're going to
calculate the area of a rectangle
what I like to do when creating a
project is declare all of my variables
at the top again make sure that you're
importing the scanner class I will
create a double variable of width I'll
set that to be
zero and a double variable of height also
also
zero and double
area I will set that to be
zero we're going to accept some user input
input
and reassign width and
height so we need a scanner object to
accept user input scanner scanner equals
new scanner parentheses semicolon within
the parenthesis we will type
system.in and again since we're opening
a scanner it's good practice to close it
I sometimes forget to do that scanner.
close we'll create a prompt to tell the
user to enter in a width we can use
system.out.print line or print for
prompts I like to use
print enter the
width we will take our width we've
already declared our width once we don't
need to type the data type again we can
reuse it width equals use our scanner
object use the an next Double method
because we're accepting a double a width
let's do this with height I'll just copy
height all right let's test it
currently let's make up some numbers 3.1 and
and
4.2 all right once we have the width and
the height we have to calculate the area
so we're going to take our area variable equals
equals
height and then let's output
it system.out.print line the area
is plus our variable
area so let's say 3.2 and
after area We'll add centimeters you
could do centimet squared if you prefer
or you could even add a superscript of
two so if you're on Windows make sure
num lock is on hold alt then type 0178
on the
numpad if you would like a superscript
of two you know because we're working with
with
areas so let's say
5.3 and
we're going to create a game of Mad Libs
Mad Libs is a game where you have a
story and a user fills in different
words the result is that it gives you a
story that's really silly or doesn't
necessarily make sense at times but
that's what we'll be doing in this video
it will help us practice accepting user
input since we're accepting user input
we'll need to import the scanner class
at the top of our Java file import java.util.scanner
java.util.scanner
a scanner is going to help us accept
user input we'll declare that and assign
it scanner scanner equals new scanner parenthesis
parenthesis
semicolon then within the parenthesis we
system.in when writing a program I like
to declare all of my variables first all
these variables are going to be of the
string data type we will need an
adjective you're going to get an English
lesson today
too adjective one an adjective describes
something like Fast slow cheap
expensive we'll need a noun string noun
one a noun is a person place or thing
we'll need another
adjective adjective
two we'll need a verb a verb is an
action like sleeping or running verb one
then another adjective a again an
adjective describe something all right
so let's work on our
lines so for the first line we'll say
today I went to
a we'll insert an adjective adjective
one we're going to describe a zoo that
we went to
we haven't asked for user input yet
we're getting a warning that this
variable has not been initialized that's
okay we'll take care of that
soon so today I went to a a description
an adjective
exhibit I saw
a plus a noun a noun is a person place
or thing like a gorilla or
harambe then we'll add some punctuation a
a
and our verb verb one then add some punctuation
so we could say that harambe was big and
action I
was plus adjective
three then add some
punctuation all right now we just need
to accept user input so let's do that
after assigning the variables we'll need
statements we will prompt the user to
enter an
adjective enter an adjective I'll give a
hint that an adjective is a
something enter a
noun I'll give a hint that we are
looking for
person we'll need another adjective we
can just copy this
line then we need a
verb enter a verb and we want it in
present tense so ending with ing like
running I'll give a hint that a verb is an
an
action and then another
adjective all right now we just need to
assign these variables we've already declared
declared
them adjective one equals take our
method and really we can just copy this
line paste it and then change what we're
assigning it to
we're accepting strings for each of
these lines we have adjective one noun
one adjective
2 verb one and adjective
3 all right now the last thing that I'm
forgetting since we opened up a scanner
it is good practice to close it at the
end of our file if we don't it can lead
to unexpected Behavior if we leave any open
open
resources scanner. close all right we
are ready to run this
I'm going to prefix a new line character
before displaying our
story just so that it's not so close to
the prompts when outputting
it enter an adjective a
suspicious enter a noun so I like making
fun of Mark Zuckerberg I'm going to
write the name of a person Mark
Zuckerberg enter an adjective
smelly enter a verb ending with ing
ing
screaming enter an adjective
happy and here's our Mad Libs game today
I went to a suspicious zoo in an exhibit
I saw a Mark
Zuckerberg Mark Zuckerberg was smelly
and screaming I was happy so for your
Mad Libs game post your results in the
comment section because I would like to
read them I want to see what you you
guys wrote or if you wrote a different
story post that too and well everybody
that is a simple Mad Libs game that we
Java all right everybody so we got a
really important topic to discuss today
although I can be a little dry and that
is the use of different arithmetic
operators in Java when it comes to
programming you got to math sometimes
it's a pretty important topic so let's
start with some basic addition in this
demonstration we will have three
variables X will equal 10 y will equal 2
and Z will store the result we'll
declare it but not yet assign it so for
basic addition we'll store our result
within z z equals X for addition you can
use the plus sign
Y what is 10 + 2 then we'll display
it we're storing the result within
Z which gives us 12
then we have
subtraction z = x -
y 10 - 2 is 8
8
multiplication for multiplication we're
going to use an asterisk 10 *
2 is
20 for division we use a forward slash z
= x / y 10 /
2 is
5 there's also the modulus operator
which is a percent sign that would give
you the remainder of any
division Z is going to store the
remainder this time x modulus y so
modulus is a percent sign 10 divides by
two evenly so the remainder is going to be
be
zero but if we divided 10 by three that
doesn't divide evenly
10 modulus 3 gives us a remainder of one
the modulus operator is really useful if
you need to determine if a number is
even or not or when working with time
you need to see if something is
divisible by 60 seconds or 60
minutes we'll get more into that later
but you should at least know what the
modulus operator
is now we have something called
augmented assignment operators instead
of storing the result within Z this time
we're going to reassign the result to
variable X so let's say we would like to
add 10 and 3 together but store it
within X well we could say x = x + y
this would technically
work so 10 + 3 is 13 but there is a
shortcut though that we could use and
that is by using augmented assignment
operators we'll condense some of these
steps instead of saying x = x + y we
simply say x + = y and that does the same
same
thing 10 + 3 is
13 there's also
subtraction x = X -
y 10 - 3 is 7 but we could condense it
to be x - equal
y that gives us
7 or multiplication x = x * y 10 * 3 is
30 but we can condense it to be x * =
y that is also
30 for division x = x /
y that gives us three now one thing to
pay attention to with division all right
so 10 / 3 should be 3.33 repeating right
well we're using something called
integer division we're not able to store
the decimal portion because we're
working with whole integers so that's
something to pay attention to when
you're using integer Division if we were
working with
doubles then we would retain that
decimal portion so do pay attention to
that we'll discuss that in another video
when it comes to typ casting for the
augmented assignment version that would
be x / = Y and let's change that to be 2
so 10 / 2 is
5 then we have the modulus operator x =
x modulus y 10 divides by 2
evenly X will be zero the augmented
assignment version of this would be X
modulus equals
y and that would also be 0o but if y were
were
three then that would be one now we have
increment and decrement operators you
see this a lot with looping structures
let's say that x equal 1 this time
instead of saying x = x + 1 which would
give us 2 or even the augmented
assignment inversion which would be X+ =
1 well there's even a shortcut for this
if we're only incrementing by one and
that is
x++ we're incrementing X by
one you tend to see this in a lot of
looping structures but that's a topic
for another day each time I increment X by
by
1 it's going to be retained so now x = 3
x ++ again well now X is
4 now there's also the decrement
operator x = X - one of course that's
going to be zero this
time so to decrement you can use x - minus so now X is zero let's do it again
minus so now X is zero let's do it again X
X -- now X is -1 x
-- now X is -1 x -- X is
-- X is -2 so those are the increment and
-2 so those are the increment and decrement operators you'll see these
decrement operators you'll see these again when we reach the topic on Loops
again when we reach the topic on Loops the last thing I need to discuss today
the last thing I need to discuss today is the order of operations and there's
is the order of operations and there's an acronym PEMDAS it's parentheses
an acronym PEMDAS it's parentheses exponents multiplication division
exponents multiplication division addition then subtraction in that order
addition then subtraction in that order you may hear the phrase to remember this
you may hear the phrase to remember this please excuse my dear Aunt Sally but I
please excuse my dear Aunt Sally but I like the phrase please excuse my dope
like the phrase please excuse my dope ass swag that's my version that I like
ass swag that's my version that I like to use let's say we have the equation
to use let's say we have the equation double result equals 3 + 4 time
double result equals 3 + 4 time parentheses 7 - 5 divided by
parentheses 7 - 5 divided by 2.0 I'm dividing by 2.0 because right
2.0 I'm dividing by 2.0 because right now we're using integer division which
now we're using integer division which we previously talked about so I'm going
we previously talked about so I'm going to use 2.0 so we retain that decimal
to use 2.0 so we retain that decimal portion again that's a topic for another
portion again that's a topic for another day let's display the
day let's display the result so I don't know what the result
result so I don't know what the result is but it is 7
is but it is 7 7.0 in what order do we solve this
7.0 in what order do we solve this equation exactly well we can use that
equation exactly well we can use that acronym of pendos
acronym of pendos from the left to the right we solve
from the left to the right we solve anything within parentheses first so
anything within parentheses first so going from the left to the right we skip
going from the left to the right we skip over any addition multiplication we're
over any addition multiplication we're looking for parentheses which we have
looking for parentheses which we have right here if you enclose part of an
right here if you enclose part of an equation within parentheses you would
equation within parentheses you would solve that first 7 - 5 is 2 there's no
solve that first 7 - 5 is 2 there's no more
more parentheses then we check any exponents
parentheses then we check any exponents there are no
there are no exponents
exponents multiplication well we have
multiplication well we have multiplication right here we would solve
multiplication right here we would solve that next 4 * 2 is 8 there's no more
that next 4 * 2 is 8 there's no more multiplication then we have
multiplication then we have division we have 8 / 2 which gives us
division we have 8 / 2 which gives us 4 then any addition 3 + 4 is 7 and that
4 then any addition 3 + 4 is 7 and that was our original result and then you
was our original result and then you would do any subtraction last so that is
would do any subtraction last so that is the order of operations when it comes to
the order of operations when it comes to arithmetic operators all right everybody
arithmetic operators all right everybody so that is some basic arithmetic and
so that is some basic arithmetic and different operators you can use in
different operators you can use in Java hey everybody so in this video
Java hey everybody so in this video we're going to create a shopping cart
we're going to create a shopping cart program a user is going to be able to
program a user is going to be able to type in an item set a price for each and
type in an item set a price for each and then ask for a quantity the output is
then ask for a quantity the output is that it's going to give you a total
that it's going to give you a total based on the price and how much you're
based on the price and how much you're buying this would be a good exercise for
buying this would be a good exercise for us to get us more comfortable with
us to get us more comfortable with accepting user input all right let's get
accepting user input all right let's get started everybody we'll need the help of
started everybody we'll need the help of a scanner the scanner allows us to
a scanner the scanner allows us to accept user input we'll need to import
accept user input we'll need to import that at the at the top so be sure that
that at the at the top so be sure that you have this line of code import
you have this line of code import java.util.scanner
java.util.scanner we'll create a scanner object scanner
we'll create a scanner object scanner scanner equals new scanner parentheses
scanner equals new scanner parentheses semicolon type
semicolon type system.in then if we open a scanner it's
system.in then if we open a scanner it's good practice to close it when we're
good practice to close it when we're done with it scanner. close if you leave
done with it scanner. close if you leave resources open it can lead to unexpected
resources open it can lead to unexpected behavior when creating a project I like
behavior when creating a project I like to declare all of my variables at the
to declare all of my variables at the top let's say we have an item name that
top let's say we have an item name that data type is going to be a string string
data type is going to be a string string item what are we buying
item what are we buying exactly we need a price that would be a
exactly we need a price that would be a double because there might be dollars
double because there might be dollars and cents a quantity how many of
and cents a quantity how many of something are we buying int quantity
something are we buying int quantity pick a unit of currency this could be a
pick a unit of currency this could be a character char
character char currency I'm going to initialize this
currency I'm going to initialize this right away American
right away American dollars and then a total we're going to
dollars and then a total we're going to multiply the price by the quantity to
multiply the price by the quantity to give a
give a total double total now if you would like
total double total now if you would like you can initialize some of these right
you can initialize some of these right away and assign them for example let's
away and assign them for example let's say we are at a pizza
say we are at a pizza restaurant I could set the item to be
restaurant I could set the item to be pizza right
pizza right away or within this program we could
away or within this program we could fill it in then let's create some
fill it in then let's create some prompts I'll use
system.out.print what item would you like to
like to buy then let's accept user input we're
buy then let's accept user input we're going to assign our string of item equal
going to assign our string of item equal to use our scanner object and use the in
to use our scanner object and use the in next line
next line method then let's just print it to
method then let's just print it to verify that it's working
what item would you like to buy maybe this time I am buying a hamburger that
this time I am buying a hamburger that will output hamburger we know that we
will output hamburger we know that we can get user input so let's delete this
can get user input so let's delete this line I was just testing it let's ask for
line I was just testing it let's ask for a
a price you could set an initial
price you could set an initial price if you would
price if you would like or we could ask for one depending
like or we could ask for one depending on how you want to write this
on how you want to write this program so let's system. about the
print what is the price for each if we're working with a price a
each if we're working with a price a double we'll use the next Double method
double we'll use the next Double method we're going to assign our price equal to
we're going to assign our price equal to use our scanner. next
use our scanner. next Double and then let's test it by
Double and then let's test it by outputting the
price okay let's say I'm buying a pizza this time what is the price for each
this time what is the price for each $4.99 and that outputs
$4.99 and that outputs $4.99 so it is a good idea every once in
$4.99 so it is a good idea every once in a while to test your code just to be
a while to test your code just to be sure that it all works as you go
sure that it all works as you go along then we'll need a
like we will assign our quantity variable
variable equals
equals scanner. next int since we're working
scanner. next int since we're working with whole numbers this
with whole numbers this time then let's test our quantity to see
time then let's test our quantity to see if it
if it works I don't know maybe I'm buying a
works I don't know maybe I'm buying a hot dog this time what is the price per
hot dog this time what is the price per each
each $4.99 how many would you like I would
$4.99 how many would you like I would like 12 hot dogs
like 12 hot dogs 12 and I'm just going to make sure I'm
12 and I'm just going to make sure I'm using print instead of print line just
using print instead of print line just because I think it looks better
now we'll create a total we don't need user input for that we're going to use
user input for that we're going to use the variables that we've already had
the variables that we've already had after assigning them total equals the
after assigning them total equals the price times the
total maybe I'm buying a pizza or pizzas each is $4.99
pizzas each is $4.99 and I buying three of
and I buying three of them
following I'm going to use a new line character just to separate our output
character just to separate our output from the
from the prompts you have
quantity plus a space character plus our variable
variable item but it might be more than one so
item but it might be more than one so let's say/ s it might be pizza or
let's say/ s it might be pizza or pizzas then we will display the price
pizzas then we will display the price including the unit of
currency your total is I'll add our unit of currency it's a
is I'll add our unit of currency it's a character I picked American dollars but
character I picked American dollars but pick whatever you would like plus our
pick whatever you would like plus our total
total that we have
that we have calculated all right let's see the
calculated all right let's see the result what item would you like to buy I
result what item would you like to buy I would like to buy a pizza what is the
would like to buy a pizza what is the price for each
price for each $4.99 how many would you like I would
$4.99 how many would you like I would like eight pizzas maybe it's for a party
like eight pizzas maybe it's for a party you have bought eight pizzas your total
you have bought eight pizzas your total is
$19.92 all right everybody so that is a shopping cart program that you can write
shopping cart program that you can write as an exercise using
Java hello everybody today we're going to discuss if statements in Java an if
to discuss if statements in Java an if statement performs a block of code if
statement performs a block of code if its condition is true we've discussed
its condition is true we've discussed how Boolean variables can be used within
how Boolean variables can be used within if statements we may be a little
if statements we may be a little familiar with them already in this
familiar with them already in this demonstration we will have a variable of
demonstration we will have a variable of age set it equal to be some
age set it equal to be some age age will be an integer I would like
age age will be an integer I would like to check if my variable of age is
to check if my variable of age is greater than or equal to 18 if so we can
greater than or equal to 18 if so we can print a message that you are an adult to
print a message that you are an adult to write an if statement will type if
write an if statement will type if parentheses curly braces within the set
parentheses curly braces within the set of curly braces we can check a condition
of curly braces we can check a condition to see if it's true so let's check to
to see if it's true so let's check to see if age is greater than or equal to
18 if that's true we'll print the following you are an
adult that would result in US outputting you are an
you are an adult now if this condition was false if
adult now if this condition was false if it's not true let's say that my age is
it's not true let's say that my age is 12 well then we skip over the if
12 well then we skip over the if statement we check if this condition is
statement we check if this condition is true if it is we perform this code if
true if it is we perform this code if not we skip it alternatively we could
not we skip it alternatively we could add an else clause
add an else clause this would be another statement we would
this would be another statement we would add else if this is false then do
add else if this is false then do something else so let's output the
something else so let's output the following you are a
following you are a child since the age is 12 we would
child since the age is 12 we would output you are a
child there's also an else if Clause so we have one of two
we have one of two possibilities do this or do that now we
possibilities do this or do that now we could add something called else if
could add something called else if Clause let's check else
Clause let's check else if age is less than
if age is less than zero if this statement is
zero if this statement is true then let's say you haven't been
true then let's say you haven't been born
born yet now we're doing one of three
yet now we're doing one of three things but it all depends on these
things but it all depends on these conditions our else Clause is kind of
conditions our else Clause is kind of like the default if none of the above
like the default if none of the above conditions are
conditions are true so let's test this my age variable
true so let's test this my age variable is set to
is set to 19 this would display you are an
19 this would display you are an adult if my age variable was -1 we would
adult if my age variable was -1 we would display you haven't been born
display you haven't been born yet this statement was false so we go
yet this statement was false so we go down to the next
down to the next one this is true NE 1 is less than zero
one this is true NE 1 is less than zero so we do
so we do this or if I was 10
this or if I was 10 well then these top two conditions are
well then these top two conditions are both false so we do whatever is within
both false so we do whatever is within the lse
the lse statement you can add as many else if
statement you can add as many else if Clauses as you would
Clauses as you would like so here's another
one else if our variable age is equal to zero
if our variable age is equal to zero exactly double equals is the comparison
exactly double equals is the comparison operator we're checking if a variable or
operator we're checking if a variable or a value is equal to another value or
a value is equal to another value or variable you don't want to use single
variable you don't want to use single equals because that's the assignment
equals because that's the assignment operator Java thinks we're trying to
operator Java thinks we're trying to assign a variable when making a
assign a variable when making a comparison you use double
comparison you use double equals is our variable age equal to
equals is our variable age equal to zero then we'll print something else
zero then we'll print something else okay we're going to print you are a
okay we're going to print you are a baby I will set variable H to be zero
baby I will set variable H to be zero you are a baby because our variable age
you are a baby because our variable age is equal to zero
is equal to zero exactly let's add another L
exactly let's add another L statement there's something I want to
statement there's something I want to demonstrate let's check to
demonstrate let's check to see if age is greater than or equal to
see if age is greater than or equal to 65 then we will print you are a
65 then we will print you are a senior I'll set age to be 70
senior I'll set age to be 70 here's the
here's the result you are an adult so why did we
result you are an adult so why did we print this statement rather than this
print this statement rather than this one well with these if statements we
one well with these if statements we check them from the top down this
check them from the top down this condition is technically true as well as
condition is technically true as well as this one 70 is greater than or equal to
this one 70 is greater than or equal to 18 so we execute this code and skip over
18 so we execute this code and skip over the rest even though this one is also
the rest even though this one is also true you do have to pay attention to the
true you do have to pay attention to the positioning of your if and else if
positioning of your if and else if statements in this situation it would be
statements in this situation it would be better if we were to check to see if
better if we were to check to see if somebody's age was greater than or equal
somebody's age was greater than or equal to 65 first so let's turn this into the
to 65 first so let's turn this into the if
statement and then where we check if age is greater than or equal to 18 we will
is greater than or equal to 18 we will use an else if Clause instead now this
use an else if Clause instead now this should
work you are a senior but if the age was 50
well then you are an adult now we're going to modify this program
going to modify this program slightly this time we will ask for user
slightly this time we will ask for user input we'll need the help of a scanner
input we'll need the help of a scanner at the top of our Java file we're going
at the top of our Java file we're going to import
to import java.util dothe class of
java.util dothe class of scanner we'll need to create a scanner
scanner we'll need to create a scanner object scanner scanner equals new
object scanner scanner equals new scanner within the set of parentheses
scanner within the set of parentheses type system.in
type system.in then when we open a scanner it is a good
then when we open a scanner it is a good idea to close it when we're done with
idea to close it when we're done with it just so we don't leave any resources
it just so we don't leave any resources open with our variable of age we're
open with our variable of age we're going to create a prompt to have a user
going to create a prompt to have a user enter in their age I'm going to declare
enter in their age I'm going to declare a variable of age but we'll assign it
a variable of age but we'll assign it later let's create a
later let's create a prompt enter your
prompt enter your age I'll use print instead of print
age I'll use print instead of print line and then we will assign age equal
line and then we will assign age equal to scanner. next
to scanner. next int okay let's try this
int okay let's try this again and to your age let's say that I'm
again and to your age let's say that I'm 21 you are an
adult what if I was 99 you are a senior I am negative 1 years old you
senior I am negative 1 years old you haven't been born
haven't been born yet I am zero exactly you are a
yet I am zero exactly you are a baby or maybe I'm 10 you are a
baby or maybe I'm 10 you are a child so with if statements we check a
child so with if statements we check a condition if it's true we do it we do
condition if it's true we do it we do this code if not we don't otherwise we
this code if not we don't otherwise we can check another condition with else if
can check another condition with else if and if none of these conditions are true
and if none of these conditions are true we can perform whatever is within an
we can perform whatever is within an else statement else acts like the
else statement else acts like the default code if none of the above
default code if none of the above conditions are true now this time we're
conditions are true now this time we're going to work with strings
going to work with strings we're going to create a variable of name
we're going to create a variable of name and it's going to be a string we'll
and it's going to be a string we'll declare it but not yet assign
declare it but not yet assign it we will prompt the user to enter in
it we will prompt the user to enter in their name I will use print instead of
their name I will use print instead of print
print Line enter your
Line enter your name we will assign our variable of name
name we will assign our variable of name equal to scanner. next line to get a
equal to scanner. next line to get a line of text
this group of if else if and else statements let's set this to be group
statements let's set this to be group two we're going to create another
set this will be group one for the name when somebody enters in their name
name when somebody enters in their name they could skip the prompt like this
they could skip the prompt like this enter your name I'm just going to hit
enter your name I'm just going to hit enter to skip
enter to skip it we will check if our name variable is
it we will check if our name variable is empty here's how
empty here's how if we'll check if our name is empty
if we'll check if our name is empty there's a string method for this we
there's a string method for this we haven't discussed string Methods yet
haven't discussed string Methods yet instead of saying name is equal to an
instead of saying name is equal to an empty space there is a built-in method
empty space there is a built-in method of strings and that is to take our
of strings and that is to take our variable name dot is
variable name dot is empty this is another way to check to
empty this is another way to check to see if a string is empty this will be
see if a string is empty this will be our condition is empty will give you a
our condition is empty will give you a Boolean of true or false
Boolean of true or false so let's print the following if our name
so let's print the following if our name variable is
variable is empty let's say you didn't enter your
empty let's say you didn't enter your name else if our name is not empty that
name else if our name is not empty that means somebody typed in their name let's
means somebody typed in their name let's say hello plus name and I'll add an
say hello plus name and I'll add an exclamation
exclamation point okay let's try this
point okay let's try this again enter your name if I hit enter
again enter your name if I hit enter we'll perform then whatever is within
we'll perform then whatever is within the if statement then enter an age you
the if statement then enter an age you didn't enter your name you are an adult
didn't enter your name you are an adult this time let's type in our name our
this time let's type in our name our first
name hello whatever your name is you are an
an adult this time we have two groups of if
adult this time we have two groups of if else statements group one is for the
else statements group one is for the name group two is for the user's age
name group two is for the user's age this time let's create a
this time let's create a Boolean Boolean is
student then we'll create a prompt let's ask are you a student but
prompt let's ask are you a student but we need a value of true or
we need a value of true or false cuz booleans can only be true or
false cuz booleans can only be true or false
false normally is student equals use our
normally is student equals use our scanner to get some user input next
Boolean now we'll create another group of if and lse if
of if and lse if statements group
statements group three we need an if
statement so with booleans we could say is student is equal to true but there is
is student is equal to true but there is a way to simplify this a
a way to simplify this a shortcut you can just say is student it
shortcut you can just say is student it holds a direct value of true or false we
holds a direct value of true or false we don't necessarily need to write like a
don't necessarily need to write like a whole condition
whole condition so if we're a student we'll
so if we're a student we'll output you are a
output you are a student else if a student is
student else if a student is false then we'll output you are not a
false then we'll output you are not a student we have three groups of if else
student we have three groups of if else statements group three is for is
statements group three is for is student group two is for the
student group two is for the age group one is for the
age group one is for the name just to make this more fun I'm
name just to make this more fun I'm going to add some emojis I think it
going to add some emojis I think it would make it more interesting but you
would make it more interesting but you don't have to so if somebody doesn't
don't have to so if somebody doesn't enter their name I'm going to add a
enter their name I'm going to add a pouting
pouting face if somebody enters their name I
face if somebody enters their name I will add a smiley
will add a smiley face if somebody is a senior maybe we
face if somebody is a senior maybe we can find an emoji for a
adult you haven't been born yet uh we could do like a spirit or
something you are a baby you are a
school you are not a student we could do an
an office all right so this is our final
office all right so this is our final program
again we have three groups of if statements this time one for the name
statements this time one for the name one for the age and one for is student
one for the age and one for is student and then for the prompt for are you a
and then for the prompt for are you a student I'm going to use print instead
student I'm going to use print instead of print
line here's the result enter your name enter your age are you a
student hello your name you are an adult you are not a student
you are not a student let's try some of the other statements
let's try some of the other statements I'm not going to enter a name for the
I'm not going to enter a name for the age let's say that I'm
age let's say that I'm ne1 are you a student
ne1 are you a student true you didn't enter your name you
true you didn't enter your name you haven't been born yet you are a
haven't been born yet you are a student so those are if statements
student so those are if statements everybody they perform a block of code
everybody they perform a block of code if its condition is true check a
if its condition is true check a condition if it's true do this if not
condition if it's true do this if not you can do something else and well
you can do something else and well everybody that summar mizes if
everybody that summar mizes if statements in
statements in Java hey everybody in this video I'm
Java hey everybody in this video I'm going to show you how we can work with
going to show you how we can work with the random class and generate some
the random class and generate some random numbers let's begin to work with
random numbers let's begin to work with random numbers we'll need to import the
random numbers we'll need to import the random class at the top of our Java file
random class at the top of our Java file we will import java. u.
we will import java. u. random much like what we do with the
random much like what we do with the scanner class we're going to follow a
scanner class we're going to follow a similar pattern for creating a random
similar pattern for creating a random object much like a scanner object we
object much like a scanner object we will type the name of the class random
will type the name of the class random the name of the random object random
the name of the random object random equals new
equals new random so random random equals new
random so random random equals new random let's say we have an integer an
random let's say we have an integer an integer variable of number I'm going to
integer variable of number I'm going to assign our number variable equal to and
assign our number variable equal to and here's where we'll generate a random
here's where we'll generate a random number we will take our random object
number we will take our random object then we will use the next int method
then we will use the next int method this will generate a random number
this will generate a random number however there's one issue with this I'm
however there's one issue with this I'm going to print our
going to print our number the number is going to be very
number the number is going to be very large so the random number that's
large so the random number that's generated it's going to be within a
generated it's going to be within a range between just about -2 billion and
range between just about -2 billion and positive2 billion I'm guessing you don't
positive2 billion I'm guessing you don't want a number that big So within the
want a number that big So within the next integer method we can set some
next integer method we can set some bounds if I would like a random number
bounds if I would like a random number between 1 and six like I'm rolling a
between 1 and six like I'm rolling a dice or die I would say 1 comma 6 this
dice or die I would say 1 comma 6 this is actually going to give us a random
is actually going to give us a random number between 1 and
five the first number is inclusive the second number is exclusive no matter how
second number is exclusive no matter how many times I rerolled this die I'm never
many times I rerolled this die I'm never going to get
six since this number is exclusive I'm going to inrease this to be seven that
going to inrease this to be seven that will give us 1 through
six and there's six let's say this time you would like three random numbers
you would like three random numbers you're rolling three dice let's say we
you're rolling three dice let's say we have number one number two and number
have number one number two and number three all
three all integers we'll assign number one with a
integers we'll assign number one with a random integer and we'll do this with
random integer and we'll do this with numbers two and three as well number one
numbers two and three as well number one number two number number
number two number number three then we will print them number one
three then we will print them number one number two number
three 2 46 23 4
46 23 4 225 good enough for random numbers
225 good enough for random numbers between 1 and 100 the second number is
between 1 and 100 the second number is going to be 101 because it's
going to be 101 because it's exclusive so now we're generating three
exclusive so now we're generating three random numbers between 1 and 100
not only can you generate random numbers you can Generate random
number let's change the data type and number to be
double we're going to use the next Double method
this is going to generate a random number between zero and
number between zero and one just the decimal portion
really you can also generate a Boolean this might be good in a situation where
this might be good in a situation where you need to flip a coin let's say we
you need to flip a coin let's say we have a Boolean of is
have a Boolean of is heads when we flip a coin is it heads
random. nextext Boolean then we will display if the coin
Boolean then we will display if the coin we flip is heads or not is it heads or
we flip is heads or not is it heads or it's Tails that's true it is
it's Tails that's true it is heads now it's false it's
heads now it's false it's Tails we could even use an if
Tails we could even use an if statement if is heads if our coin flip
statement if is heads if our coin flip is on
is on heads let's
heads let's print heads
print heads else we will
else we will print
Tails so this will simulate us flipping a
Tails all right everybody that is how you can Generate random numbers and use
you can Generate random numbers and use the random module in Java
hey everybody in this video we're going to cover some useful math related
to cover some useful math related constants and methods that you may be
constants and methods that you may be interested in as a beginner then at the
interested in as a beginner then at the end of this topic we'll cover a few
end of this topic we'll cover a few exercises let's begin if at any time you
exercises let's begin if at any time you need the value of pi there's a built-in
need the value of pi there's a built-in constant of the math class so I'm going
constant of the math class so I'm going to print the
to print the following math with a capital M Pi all
following math with a capital M Pi all capital so that would give you the value
capital so that would give you the value 3.14 and some change so instead of
3.14 and some change so instead of creating a variable for pi it's always
creating a variable for pi it's always available to you within the math class
available to you within the math class you just have to access it there's also
E this is the exponential constant also known as ul's number you may never use
known as ul's number you may never use this but it's available to you in case
this but it's available to you in case you do so again access the math class
you do so again access the math class Dot to name the
Dot to name the constant this time let's create a double
constant this time let's create a double variable named result here's a few
variable named result here's a few methods I'm going to reassign result
methods I'm going to reassign result equal to access math dot to raise a base
equal to access math dot to raise a base to a given power you can use the pal
to a given power you can use the pal method let's raise 2 to the^ of 3 then
method let's raise 2 to the^ of 3 then print
print it let's print our variable result 2 ^
it let's print our variable result 2 ^ of 3 would be 8
of 3 would be 8 and again I'm using a double that's why
and again I'm using a double that's why we have the decimal portion 2^ of 4
we have the decimal portion 2^ of 4 would
would be 16 2 the^ of
be 16 2 the^ of 5 is
5 is 32 po meaning power you can raise a base
32 po meaning power you can raise a base to a given power these can be values or
to a given power these can be values or variables there's the absolute value
variables there's the absolute value method math.abs for absolute value
method math.abs for absolute value what's the absolute value
of5 that would be five positive 5 basically speaking the absolute value
basically speaking the absolute value method gives you that number but
method gives you that number but positive if it's negative think of it as
positive if it's negative think of it as the distance away from zero if that
the distance away from zero if that helps for square root there's a square
helps for square root there's a square root method result equals
root method result equals math.sqrt
math.sqrt what is the square root of 9 I did make
what is the square root of 9 I did make a spelling mistake here if you're
a spelling mistake here if you're accessing the math class make sure it's
accessing the math class make sure it's with a capital m so the square root of 9
with a capital m so the square root of 9 would be
3 we can also round a number again access the math class use
number again access the math class use the round
method let's round 3.14 round will round a number to the
3.14 round will round a number to the nearest whole
integer again we're working with the double though so that gives us
3.0 to always round up there's the ceiling
ceiling method math. c
method math. c l again I accidentally used lowercase M
l again I accidentally used lowercase M it's capital M let's round 3.14 up to
it's capital M let's round 3.14 up to the
the ceiling so 3.14 rounded up is four to
ceiling so 3.14 rounded up is four to always round down you can use the floor
always round down you can use the floor method
method math.
math. floor so this time let's round 3.99 down
floor so this time let's round 3.99 down normally it should round up
normally it should round up right so 3.99 rounded down is
right so 3.99 rounded down is three you can find the max between two
three you can find the max between two values or variables
values or variables math. Max method we'll have two numbers
math. Max method we'll have two numbers which are comma separated 10 and 20 what
which are comma separated 10 and 20 what is the max between these two values or
is the max between these two values or variables
the greater number is 20 there's also Min I'll just copy this cuz I'm lazy
Min I'll just copy this cuz I'm lazy replace Max with Min what is the minimum
replace Max with Min what is the minimum value between these two
value between these two values that would be
values that would be 10 so those are a few useful math
10 so those are a few useful math methods and constants that you may be
methods and constants that you may be interested in we're going to cover some
interested in we're going to cover some math related exercises if you would like
math related exercises if you would like additional practice
in this first exercise we're going to find the hypotenuse of a right triangle
find the hypotenuse of a right triangle you can follow this formula C the
you can follow this formula C the hypotenuse equals the square root of a^
hypotenuse equals the square root of a^ 2 one of the sides plus b^2 the other
2 one of the sides plus b^2 the other side we're going to accept some user
side we're going to accept some user input we'll need a scanner we need to
input we'll need a scanner we need to import the scanner class import
import the scanner class import java.util do
java.util do scanner then we'll create a scanner
scanner then we'll create a scanner object scan scanner scanner equals new
object scan scanner scanner equals new scanner then place system.in within the
scanner then place system.in within the set of
set of parentheses then when we open a scanner
parentheses then when we open a scanner it is a good idea to close it so we
it is a good idea to close it so we don't leave any resources open scanner.
don't leave any resources open scanner. close we'll prompt the user to enter in
close we'll prompt the user to enter in the length of side A and B let's declare
the length of side A and B let's declare those as variables double a double b
those as variables double a double b we'll also declare Double C that will
we'll also declare Double C that will store the hypotenuse
store the hypotenuse Double
Double C we'll need two
C we'll need two prompts I will use print instead of
prompts I will use print instead of print
print Line enter the length of side
a with inside a within our variable of a we'll assign it to scanner. next
we'll assign it to scanner. next Double let's do this with side B we can
Double let's do this with side B we can copy these two lines paste them replace
copy these two lines paste them replace a with
a with B that is lowercase
B that is lowercase b let's do a test run just to be sure
b let's do a test run just to be sure that these two work
that these two work temporarily I'm going to print a then
B enter the length as side a 3 B will be four these work I just wanted to test
four these work I just wanted to test that it is a good idea to test your code
that it is a good idea to test your code as you're writing it then we have to
as you're writing it then we have to follow this
follow this equation C equals math. square root of
equation C equals math. square root of a^2 +
a^2 + b^2 there is a square root method within
b^2 there is a square root method within the math class but we have to raise side
the math class but we have to raise side a to the power of two plus b to the^ of
a to the power of two plus b to the^ of two here's how we can do that so within
two here's how we can do that so within the square root method we're going to
the square root method we're going to raise a to the power of two first math
raise a to the power of two first math po to raise a base to a given power
po to raise a base to a given power raise a comma to the power of
raise a comma to the power of two plus again math.pow to raise a base
two plus again math.pow to raise a base to a given power B to the power of
to a given power B to the power of two and that's it so let's display
two and that's it so let's display whatever C is the
hypotenuse the
the hypotenuse I'll write that this is C
hypotenuse I'll write that this is C side
C is the following plus
C if side a is three side B is four side C should be five which it is if you
C should be five which it is if you would prefer we can add a unit of
would prefer we can add a unit of measurement such as centimet or inches
measurement such as centimet or inches so after side C add cm for centimet or I
so after side C add cm for centimet or I for inches whatever you
for inches whatever you prefer so let's try that again side a
prefer so let's try that again side a will be four side B will be
will be four side B will be five and side C is this really long
five and side C is this really long number we haven't talked about the print
number we haven't talked about the print F statement yet using print F you can
F statement yet using print F you can display a given amount of digits but we
display a given amount of digits but we do have centimeters at the end which is
do have centimeters at the end which is what we were looking for so let's try
what we were looking for so let's try three and four and that gives us 5
three and four and that gives us 5 cm all right let's cover another
exercise given the radius of a circle or a sphere we'll return the circumference
a sphere we'll return the circumference the area then the volume that's if we're
the area then the volume that's if we're working with the sphere given the radius
working with the sphere given the radius so be sure that we're importing our
so be sure that we're importing our scanner at the top and we'll create a
scanner at the top and we'll create a scanner object scanner scanner equals
scanner object scanner scanner equals new
new scanner system.in then be sure to close
scanner system.in then be sure to close your
your scanner scanner .
scanner scanner . close we'll prompt the user for a
close we'll prompt the user for a radius because we need a radius to work
radius because we need a radius to work with we'll create a variable it will be
with we'll create a variable it will be a double named radius we'll declare it
a double named radius we'll declare it but not yet assign
but not yet assign it we'll prompt the user using print
it we'll prompt the user using print instead of print
instead of print Line enter the
Line enter the radius then we will assign our radius
radius then we will assign our radius variable radius
variable radius equals scanner.
equals scanner. next
next Double once we have a radius we have to
Double once we have a radius we have to follow these formulas so we need a
follow these formulas so we need a circumference area and volume let's
circumference area and volume let's declare those at the top of our program
declare those at the top of our program but assign them later double
but assign them later double circumference I think I spelled that
right double area double
area double volume we will calculate the
volume we will calculate the circumference
here's the Formula 2 times we need pi to work with
Formula 2 times we need pi to work with instead of typing
instead of typing 3.14159 so on and so forth we can access
3.14159 so on and so forth we can access that from the math class
that from the math class math.pi Pi is always available to
math.pi Pi is always available to us then multiply this by the
us then multiply this by the radius let's perform a test
radius let's perform a test run I will display the circumference
run I will display the circumference the
the circumference
circumference is plus our variable of
is plus our variable of circumference then I'll add a unit of
circumference then I'll add a unit of measurement afterwards centimeters is
measurement afterwards centimeters is good or whatever you
prefer enter the radius I'll enter in five the circumference is 31.4 CM in the
five the circumference is 31.4 CM in the future using print F we can limit the
future using print F we can limit the amount of digits that are displayed I'll
amount of digits that are displayed I'll show you how to do that later on in this
show you how to do that later on in this video then we need the
video then we need the area area
area area equals here's the formula again we need
equals here's the formula again we need Pi Pi is always available to us math. pi
Pi Pi is always available to us math. pi times our radius to the^ of two so we
times our radius to the^ of two so we need the power method of math
need the power method of math math.pow raise the radius to the power
math.pow raise the radius to the power of
of two and I'll just copy this line because
two and I'll just copy this line because I'm
I'm lazy the area is our variable area now
lazy the area is our variable area now when working with an area the unit of
when working with an area the unit of measurement is going to be squared so we
measurement is going to be squared so we can raise it to the power of two or you
can raise it to the power of two or you can use superscript to if you're on
can use superscript to if you're on Windows make sure numlock is on hold alt
Windows make sure numlock is on hold alt then on the numpad type
then on the numpad type 0178 for a superscript of two if you
0178 for a superscript of two if you would like to use that
would like to use that instead so now what is the
instead so now what is the area enter the radius 5
area enter the radius 5 the area is 78.53982
doubles times math. pi and again make sure the m is
3 math. power method raise our radius to the power of
three then display the volume the volume is our variable volume cm
is our variable volume cm cubed for a superscript of three make
cubed for a superscript of three make sure numb lock is on hold alt then type
sure numb lock is on hold alt then type 0179 that's if you're on
0179 that's if you're on Windows all right let's print the
Windows all right let's print the volume again my radius is
volume again my radius is five then we have the
five then we have the circumference the area and the
circumference the area and the volume and the unit of measurement is
volume and the unit of measurement is cenm cubed now we haven't talked about
cenm cubed now we haven't talked about the print F statement we could display
the print F statement we could display just a few digits here's
just a few digits here's how again this is a future topic replace
how again this is a future topic replace print line with print
F instead of adding plus our variable name we're going to add a
name we're going to add a placeholder
placeholder percent F to display a double but if you
percent F to display a double but if you would like one digit between the percent
would like one digit between the percent and F type .1 so let's do this with area
and F type .1 so let's do this with area and
and volume replace the plus with a
comma then instead of adding plus centim after our
after our placeholder add
placeholder add CM then cm
CM then cm squar and cm
squar and cm cubed then we can get rid of the portion
cubed then we can get rid of the portion where we add the centimeters to the end
so let's say the radius is five then we should add a new line character to the
should add a new line character to the end of each of
these that looks much better we're only displaying one digit
better we're only displaying one digit after the decimal again don't worry
after the decimal again don't worry about this this is a future topic the
about this this is a future topic the print F statement but if you would only
print F statement but if you would only like to display one digit that's how you
like to display one digit that's how you can do that again we'll cover this later
can do that again we'll cover this later all right everybody so those are a few
all right everybody so those are a few math related constants and methods that
math related constants and methods that you may be interested in as a
beginner what's up everybody in this video I'm going to discuss the print F
video I'm going to discuss the print F statement in Java print f is a method
statement in Java print f is a method used to format output we already do have
used to format output we already do have a little bit of experience using print F
a little bit of experience using print F in the last few topics involving math
in the last few topics involving math we'll get more in depth with the print F
we'll get more in depth with the print F stat in this topic print f is an
stat in this topic print f is an alternative to print and print line
alternative to print and print line wherever we would like to insert a
wherever we would like to insert a variable we can add a placeholder of a
variable we can add a placeholder of a percent sign then add one of a few
percent sign then add one of a few characters following it to format the
characters following it to format the output in this demonstration let's
output in this demonstration let's create a few variables let's create a
create a few variables let's create a string of name I'll assign some name
string of name I'll assign some name I'll pick SpongeBob because many people
I'll pick SpongeBob because many people know who SpongeBob is we'll need a
know who SpongeBob is we'll need a character let's say character first
character let's say character first letter equals
letter equals s int age equals
s int age equals 30 and a double double
30 and a double double height equals
height equals 60.5 and a Boolean Boolean is
60.5 and a Boolean Boolean is employed I will set that to be true
employed I will set that to be true SpongeBob is employed at the K crusty
SpongeBob is employed at the K crusty Krab so we have some variables they're
Krab so we have some variables they're all different data types we can insert
all different data types we can insert them into print F statements when we
them into print F statements when we output string literal here's a
demonstration instead of using print line I'm going to use print
line I'm going to use print F we will display the
F we will display the following
following hello then I would like to insert this
hello then I would like to insert this variable of name we're going to use a
variable of name we're going to use a percent sign as a
percent sign as a placeholder percent then we need a
placeholder percent then we need a specifier our character what is the data
specifier our character what is the data type of the variable we're trying to
type of the variable we're trying to insert if you're trying to insert a
insert if you're trying to insert a string you're going to use a lowercase
string you're going to use a lowercase s so after this word of hello we're
s so after this word of hello we're adding a placeholder then inserting a
adding a placeholder then inserting a string at this location so instead of
string at this location so instead of adding plus the variable
adding plus the variable name we're going to comma separate any
name we're going to comma separate any variables we're inserting so comma name
variables we're inserting so comma name here's the
output hello our variable name which contains
contains SpongeBob if we need to insert a
SpongeBob if we need to insert a character that would be lower case C so
character that would be lower case C so let's use
let's use system.out.print
system.out.print F I don't know let's say your name
F I don't know let's say your name starts with a we're going to insert a
starts with a we're going to insert a variable we need a placeholder that
variable we need a placeholder that perent sign lower case C for a Char
perent sign lower case C for a Char variable then comma separate any
variable then comma separate any variables comma our variable of first
letter so here's an important thing too with a print F statement we have to
with a print F statement we have to manually insert any new line characters
manually insert any new line characters we'll end each print F statement with a
we'll end each print F statement with a new line
new line character so after our format specifier
character so after our format specifier We'll add back sln to insert a new
line that's better otherwise the output is going to be all on the same
is going to be all on the same line so that's how to insert a character
line so that's how to insert a character percent C for
percent C for chars then for an integer we use
chars then for an integer we use D so print
f u r we're going to insert a variable we use D for
we use D for integers you are our variable age years
integers you are our variable age years old than a new line character then we
old than a new line character then we will insert our variable
age you are 30 years old and in the middle is our variable of
and in the middle is our variable of age for a double that would be
f system.out.print
f you are add a placeholder f for floating Point number think of that as a
floating Point number think of that as a double inches tall or you can pick
double inches tall or you can pick centimeters up to you
centimeters up to you then we will insert our variable of
height you are 60.5 then a bunch of zeros inches tall
60.5 then a bunch of zeros inches tall we can limit the amount of digits that
we can limit the amount of digits that are displayed after the decimal we'll
are displayed after the decimal we'll have to set a Precision but I'll explain
have to set a Precision but I'll explain that
that later then a Boolean all we need is the
later then a Boolean all we need is the letter
letter b
b system.out.print
system.out.print f let's say
f let's say employed add a
employed add a placeholder B then a new line
placeholder B then a new line character we will display our variable
character we will display our variable of is
employed employed then our variable of true now you can insert multiple
true now you can insert multiple variables within the same line here's
variables within the same line here's how we'll use
how we'll use system.out.print
system.out.print f we're going to inst insert our
f we're going to inst insert our variable of name
variable of name SpongeBob for a string the specifier
SpongeBob for a string the specifier character is going to be lowercase s for
character is going to be lowercase s for a string so string SpongeBob
a string so string SpongeBob is we're inserting an integer we need
is we're inserting an integer we need percent
percent D years old we'll comma separate all
D years old we'll comma separate all variables we're inserting we have a
variables we're inserting we have a string followed by an integer so that
string followed by an integer so that would be name comma age we're inserting
would be name comma age we're inserting two variables of this time SpongeBob is
two variables of this time SpongeBob is 30 years
30 years old so those are specifier characters
old so those are specifier characters add a percent sign a placeholder then
add a percent sign a placeholder then follow this placeholder with a specifier
follow this placeholder with a specifier character depending on what the data
character depending on what the data type is s for Strings C for
type is s for Strings C for chars D for integers f for doubles or
chars D for integers f for doubles or other floating Point numbers and B for
other floating Point numbers and B for booleans it might take a little bit of
booleans it might take a little bit of time to remember
time to remember these now we'll cover Precision with
these now we'll cover Precision with setting the Precision we can limit the
setting the Precision we can limit the amount of digits that display after a
amount of digits that display after a decimal let's create three different
decimal let's create three different prices and these will be of the double
prices and these will be of the double data type price 1 equals
$9.99 price two I'm just making up numbers here
10.15 and double price 3 equals 5
equals 5 $41 we're going to use print F to
$41 we're going to use print F to display these
display these prices
prices system.out.print F we're going to insert
system.out.print F we're going to insert we'll use that percent placeholder then
we'll use that percent placeholder then use f to display a double f for floating
use f to display a double f for floating Point
Point number comma our variable of price one
number comma our variable of price one then we'll do this with price two and
then we'll do this with price two and price
price three price one price two price three
three price one price two price three and here are the prices oh and we have
and here are the prices oh and we have to add a new line character too because
to add a new line character too because they're all in the same line I forgot to
they're all in the same line I forgot to do that so back sln back
do that so back sln back sln back
sln back sln that's better naturally when we're
sln that's better naturally when we're using print F to display a floating
using print F to display a floating Point number such as a double normally
Point number such as a double normally it displays six digits after the decimal
it displays six digits after the decimal point but we would like to limit that
point but we would like to limit that here's how we're going to set the
here's how we're going to set the Precision
Precision to display one digit after the decimal
to display one digit after the decimal between the percent sign and the F Type
between the percent sign and the F Type .1 to display one
digit so we have 10.0 this will automatically round the
10.0 this will automatically round the output so we have 10.0 100.2 and
output so we have 10.0 100.2 and 54.0 for two digits that would be 02
999 10.15 and
10.15 and 54.1 or we could do
54.1 or we could do three
3F then we have three digits after the decimal so that is precision it's useful
decimal so that is precision it's useful for displaying prices then we have Flags
for displaying prices then we have Flags next let's set the Precision to be 0.2
here's different flags that we can add by adding a plus after the percent sign
by adding a plus after the percent sign we can output a plus for any positive
numbers positive 999 positive 10.15 54.1 is still
54.1 is still negative to display a plus before any
negative to display a plus before any positive numbers just add a plus sign
positive numbers just add a plus sign let's increase these
let's increase these prices let's add three zeros to the end
prices let's add three zeros to the end of
each if you add the flag of a comma it's a comma grouping separator for any
a comma grouping separator for any thousand's place after the percent sign
thousand's place after the percent sign add a
add a comma at any thousand's place we have a
comma at any thousand's place we have a comma grouping separator again this is
comma grouping separator again this is useful for displaying prices
by adding a single left parentheses any negative numbers are enclosed in a set
negative numbers are enclosed in a set of parentheses so let's revert these
of parentheses so let's revert these prices
prices back after the percent sign add a left
parentheses so we only have one negative price-
54.1 and then we have a space character this will display a minus if negative
this will display a minus if negative space space if positive we have two
space space if positive we have two positive numbers in one negative one so
positive numbers in one negative one so by using a space
character any positive numbers are preceded with a space 54.1 is negative
preceded with a space 54.1 is negative so we do not have that space it's good
so we do not have that space it's good for aligning
for aligning numbers the last specifier we have to
numbers the last specifier we have to talk about is
talk about is width we're going to create some ID
width we're going to create some ID numbers these will be integers int id1 =
numbers these will be integers int id1 = 1 int id2 =
1 int id2 = 23 in
23 in ID3 equal
7890 these integers have a varying number of digits 1 2 3 4 by setting the
number of digits 1 2 3 4 by setting the width we can align them here's how again
width we can align them here's how again we're going to use print F we're
we're going to use print F we're displaying an integer so we need percent
displaying an integer so we need percent D we will Begin by displaying
D we will Begin by displaying id1 then let's do this with 2 three and
id1 then let's do this with 2 three and four as
four as well 2 3
4 and again I am missing that new line character new line new line
character new line new line new
new line new
line new line that's better so we have our four
line that's better so we have our four IDs by adding a zero after the percent
IDs by adding a zero after the percent sign we can zero pad some of these
values but Java is giving us a warning by how many characters do we want to pad
by how many characters do we want to pad these numbers with
these numbers with zero let's say four we have one variable
zero let's say four we have one variable that has four digits we'll set it to be
that has four digits we'll set it to be four to be the maximum so
04 and here we are these ID numbers are all now zero
all now zero padded and they align vertically which
padded and they align vertically which is kind of
is kind of nice so to add some zero padding follow
nice so to add some zero padding follow our placeholder with zero then the
our placeholder with zero then the amount of digits to Zer pad in this case
amount of digits to Zer pad in this case four by setting a positive number we can
four by setting a positive number we can WR justify these variables
WR justify these variables so let's replace zero with just
so let's replace zero with just four rather than having that zero
four rather than having that zero padding we just have some spaces if you
padding we just have some spaces if you would prefer it that
would prefer it that way or with a negative number we can
way or with a negative number we can left justify these
left justify these values so let's set four to be instead
values so let's set four to be instead -4 now these values are left Justified
-4 now these values are left Justified and we still have those spaces
and we still have those spaces afterwards except for the last variable
afterwards except for the last variable because it's already four digits
because it's already four digits all right everybody so that is the print
all right everybody so that is the print F statement it's a method used to format
F statement it's a method used to format output you add a placeholder then one of
output you add a placeholder then one of a few characters afterwards there is
a few characters afterwards there is Flags width precision and specifier
Flags width precision and specifier characters depending on the data type of
characters depending on the data type of what you want to display we'll have more
what you want to display we'll have more practice with this in the future and
practice with this in the future and well everybody that is print F in
Java hey everybody this video serves as a project we're going to create a
a project we're going to create a compound interest calculator using Java
compound interest calculator using Java if you put money in a bank account or
if you put money in a bank account or the stock market using the given formula
the stock market using the given formula we can determine what our final amount
we can determine what our final amount is going to be plus interest after a
is going to be plus interest after a given amount of time this project serves
given amount of time this project serves as an exercise using Java let's begin
as an exercise using Java let's begin all right let's get started everybody
all right let's get started everybody the first thing we'll need is a scanner
the first thing we'll need is a scanner we'll need to import it at the top of
we'll need to import it at the top of our Java file import input
our Java file import input import
import java.util.scanner
we need to create a scanner object again scanner scanner equals new
scanner scanner equals new scanner then within the set of
scanner then within the set of parentheses type
parentheses type system.in when you open a scanner it is
system.in when you open a scanner it is good practice to close the scanner when
good practice to close the scanner when you're done with it so you don't leave
you're done with it so you don't leave any resources
any resources open after creating our scanner here the
open after creating our scanner here the different variables we'll need double
different variables we'll need double principal this will store the principal
principal this will store the principal amount what's our original investment an
amount what's our original investment an interest rate double rate
interest rate double rate an integer for times compounded how
an integer for times compounded how often does our interest compound like
often does our interest compound like yearly quarterly
yearly quarterly monthly then we need an amount of time
monthly then we need an amount of time such as years into
years and the final amount double
double amount now we have to get some user
amount now we have to get some user input we'll need some prompts first we
input we'll need some prompts first we need the principal amount all use
system.out.print enter the principal I never spell principal right enter the
never spell principal right enter the principal
amount we are working with the double so we need the next Double method of our
we need the next Double method of our scanner principal equals our
scanner principal equals our scanner do next
Double then we need the interest rate this is going to be a
this is going to be a double
system.out.print enter the interest rate I'll add within our prompt that
rate I'll add within our prompt that this is in a percentage form like 5% or
this is in a percentage form like 5% or so the number five instead of
so the number five instead of 05 so then we have our interest
05 so then we have our interest rate so we need our scanner do next
rate so we need our scanner do next double so let's say somebody types in
double so let's say somebody types in five for
five for 5% we would like the rate to be 05
5% we would like the rate to be 05 rather than 5 after accepting the user
rather than 5 after accepting the user input let's divide that number by 100 or
input let's divide that number by 100 or let's say somebody types in seven we
let's say somebody types in seven we don't want the rate to be seven we want
don't want the rate to be seven we want it to be
it to be 07 that's why we're dividing by
07 that's why we're dividing by 100 we'll fill in the times compounded
100 we'll fill in the times compounded variable we're going to use print
enter the number of times
times compounded per
compounded per year so this could be yearly that would
year so this could be yearly that would be one quarterly four or monthly would
be one quarterly four or monthly would be 12 in most cases it's probably going
be 12 in most cases it's probably going to be one for yearly times
to be one for yearly times compounded equals use our
scanner next int cuz we're accepting an
next int cuz we're accepting an integer then we need the amount of times
integer then we need the amount of times our money is going to be
invested enter the number of years then we need to assign our
years then we need to assign our variable years years equals
variable years years equals scanner. next int because we're working
scanner. next int because we're working with an integer then we need to
with an integer then we need to calculate the total amount here's the
calculate the total amount here's the formula
amount equals we need our principal
amount times access the math class use the power
the power method raay is 1 plus the interest
rate divided by the variable times compounded so this is going to be the
compounded so this is going to be the base we Comm separate the base and the
base we Comm separate the base and the power we are raising this part of our
power we are raising this part of our equation to the
equation to the power of times
power of times compounded times the number of
compounded times the number of years and that's our
years and that's our formula it's a little confusing but it
formula it's a little confusing but it should
should work then we will display the
work then we will display the amount system.out.print
amount system.out.print line the amount
after plus years plus
plus is pick a unit of currency I'll pick
is pick a unit of currency I'll pick American
dollars plus amount let's test
amount let's test this so let's say we have $10,000 or so
this so let's say we have $10,000 or so and we're putting it in the
and we're putting it in the bank what is the interest rate
bank what is the interest rate maybe
maybe 3% so I'm going to type three enter the
3% so I'm going to type three enter the amount of times compounded per year I'll
amount of times compounded per year I'll go with
go with one enter the number of years
one enter the number of years one so we should have 10,300 in our
one so we should have 10,300 in our bank which we do
bank which we do 10,300 if you would like you can use a
10,300 if you would like you can use a print F statement to format the
print F statement to format the output so if you're familiar with that
output so if you're familiar with that let's replace print line with print
let's replace print line with print F instead of concatenating these
F instead of concatenating these variables we'll add some placeholders
instead so to display an integer we need percent D within print
percent D within print F
F years is then to display a double we
years is then to display a double we need percent F then we'll list our
need percent F then we'll list our arguments
arguments years comma
amount so to display two decimals within a double between the percent and the F
a double between the percent and the F we're going to type 2 to display two
we're going to type 2 to display two digits after the
digits after the decimal we'll proceed this placeholder
decimal we'll proceed this placeholder with the unit of currency let's do
with the unit of currency let's do American dollars okay let's see the
American dollars okay let's see the total
total amount enter the principal amount
amount enter the principal amount $110,000 enter the interest rate 2%
$110,000 enter the interest rate 2% enter the number of times compounded per
enter the number of times compounded per year this time let's do quarterly so
year this time let's do quarterly so four because there's four quarters in a
four because there's four quarters in a year enter the number of years let's do
year enter the number of years let's do two
two actually and here's the amount in our
actually and here's the amount in our bank account after 2 years
$1,477 all right everybody so that is a compound interest calculator you can
compound interest calculator you can write using
Java what is going on everybody in this video I'm going to explain nested if
video I'm going to explain nested if statements in Java
statements in Java in Java it is possible to have if
in Java it is possible to have if statements within other if statements
statements within other if statements kind of like
kind of like this after checking some condition you
this after checking some condition you could follow with another condition if
could follow with another condition if the first condition is true you can add
the first condition is true you can add if
if statements L if
statements L if statements and or else
statements and or else statements really depends on the program
statements really depends on the program that you're trying to write so what
that you're trying to write so what we're going to do in this demonstration
we're going to do in this demonstration is have two Boolean
is have two Boolean variables a Boolean of is
variables a Boolean of is student let's say that we're selling
student let's say that we're selling movie tickets if somebody's a student
movie tickets if somebody's a student they get a 10% discount on their movie
they get a 10% discount on their movie ticket we also have a senior discount
ticket we also have a senior discount Boolean is
Boolean is senior if somebody is 65 or older they
senior if somebody is 65 or older they get a 20% senior
get a 20% senior discount or if they're a student and a
discount or if they're a student and a senior they get a combined total of 30%
senior they get a combined total of 30% off their ticket
off their ticket price let's say we have a double of
price let's say we have a double of price the price of a movie ticket will
price the price of a movie ticket will be $9.99 let's say that's actually kind
be $9.99 let's say that's actually kind of cheap
of cheap nowadays we'll write an if statement to
nowadays we'll write an if statement to check to see if somebody is a student if
check to see if somebody is a student if is student is equal to true but since
is student is equal to true but since this is a Boolean variable we don't need
this is a Boolean variable we don't need the equals true portion we can just say
the equals true portion we can just say if is student I will go ahead and set
if is student I will go ahead and set this to be true right away so if
this to be true right away so if somebody is a student they get a student
somebody is a student they get a student discount else they
won't so if a student is true let's output the
output the following you get a
following you get a student discount of
student discount of 10% then we will take our
10% then we will take our price price equals price time
price price equals price time 0.9 that will give you a 10% discount
0.9 that will give you a 10% discount account you could shorten this using the
account you could shorten this using the augmented assignment operator price
augmented assignment operator price times equals
times equals 0.9 that will set the price to be
0.9 that will set the price to be 90% or a 10% discount so to say if
90% or a 10% discount so to say if somebody's not a student they're going
somebody's not a student they're going to pay full price price times equals 1
to pay full price price times equals 1 that really doesn't do anything but it
that really doesn't do anything but it might help with this
might help with this visualization then we'll output the
is pick unit of currency then I'll add our price let's perform a test
our price let's perform a test run currently we're a student you get a
run currently we're a student you get a discount of 10% the price of a ticket is
$8.99 to limit the amount of digits that display let's use a printf statement
display let's use a printf statement we'll use print F instead of print line
we'll use print F instead of print line after the dollar sign I will add a
after the dollar sign I will add a format specifier we're going to display
format specifier we're going to display a double we'll use f for a floating
a double we'll use f for a floating Point
Point number comma price to display two digits
number comma price to display two digits after the decimal use 0
after the decimal use 0 2 now we can display a
2 now we can display a price you get a student discount of 10%
price you get a student discount of 10% the price of a ticket is
the price of a ticket is $8.99 now if we weren't a student I'll
$8.99 now if we weren't a student I'll set this to be
false we don't get that discount the price of a ticket is $9.99 what it was
price of a ticket is $9.99 what it was originally now what if somebody is a
originally now what if somebody is a senior and a student within our if
senior and a student within our if statement we'll write a nested if
statement we'll write a nested if statement as well as an else
statement as well as an else statement if is senior they get a
statement if is senior they get a student discount and a senior
student discount and a senior discount let's cut these two lines
discount let's cut these two lines within the if statement and stick them
within the if statement and stick them within the nested else statement
within the nested else statement if somebody is a senior and a
if somebody is a senior and a student you get a senior
20% and a student discount of 10% so let's take our original
10% so let's take our original price times equals
so let's say is senior is true for now okay else if they're not a student
now okay else if they're not a student but they are a
senior we'll check that with a nested if statement within the else
statement within the else statement if is senior they get that
statement if is senior they get that senior
senior discount but it's only 20% instead of 30
discount but it's only 20% instead of 30 because they're not also as
student price times equals 0.8 you could add
0.8 you could add else price times equals
else price times equals 1 that's if somebody is not a student
1 that's if somebody is not a student and not a senior but you don't
and not a senior but you don't necessarily need the sell
necessarily need the sell statement all right let's perform a test
run let's say that we're not a student and not a senior
the price of a ticket is $9.99 what if we were a student but not
$9.99 what if we were a student but not a
a senior you get a student discount of 10%
senior you get a student discount of 10% the price of a ticket is
the price of a ticket is $8.99 what if we're not a student but we
$8.99 what if we're not a student but we are a
senior you get a senior discount of 20% the price of a ticket is
the price of a ticket is $7.99 what if we're both a student and a
senior you get a senior discount of 20% you get a student discount of 10% the
you get a student discount of 10% the price of a ticket is
price of a ticket is $6.99 that's how nesa if statements can
$6.99 that's how nesa if statements can be useful you could check another
be useful you could check another condition after checking a condition
condition after checking a condition already so that's just one example of
already so that's just one example of nesa if statements and well everybody
nesa if statements and well everybody those are Nesta if statements in
Java hey yeah so today I'm going to show you a few useful string Methods you may
you a few useful string Methods you may be interested in as a beginner using
be interested in as a beginner using Java in this demonstration let's create
Java in this demonstration let's create a variable of name the data type is
a variable of name the data type is going to be a string type in your full
going to be a string type in your full name including a
name including a space I'll just use my YouTube channel
space I'll just use my YouTube channel name if at any time you need the length
name if at any time you need the length of a string you can use the length
of a string you can use the length method I'll store that as an integer int
method I'll store that as an integer int length equals to access these string
length equals to access these string Methods you need a string or a variable
Methods you need a string or a variable that is a string
that is a string dot then we have one of a few methods if
dot then we have one of a few methods if you need the length you can use the
you need the length you can use the length
length method and then let's print
it print the length how many characters are in the string
are in the string eight 1 2 3 4 5 6 7 8 this could be
eight 1 2 3 4 5 6 7 8 this could be useful let's say somebody is setting a
useful let's say somebody is setting a password and you have a maximum size of
password and you have a maximum size of 12 characters well you can check the
12 characters well you can check the length to see if it's under 12
length to see if it's under 12 characters so that is the length
characters so that is the length method there's Char at that will give
method there's Char at that will give you the character at a specified index
you the character at a specified index we'll be given a single character we'll
we'll be given a single character we'll store that as a variable Char letter
store that as a variable Char letter equals take our string of name use the
equals take our string of name use the Char at
Char at method within the Char at method we'll
method within the Char at method we'll list an index zero is the index of the
list an index zero is the index of the first character because computers like
first character because computers like to start at zero what what is the
to start at zero what what is the character at index
character at index zero well that letter is B at index
zero well that letter is B at index one that would be R and
one that would be R and two would be
two would be o that is the charat method it returns a
o that is the charat method it returns a character at a given index within a
character at a given index within a string we also have the capability of
string we also have the capability of finding a letter at a given
finding a letter at a given index let's say we have a variable of
index let's say we have a variable of index take our name use the index of
index take our name use the index of method find the first occurrence of an
method find the first occurrence of an O so in my example that should be 2 0 1
O so in my example that should be 2 0 1 2 that is the first index of this
2 that is the first index of this character o what about a
character o what about a space well that would be three 0 1 2
3 there's also last index last index equals take our string
index last index equals take our string of
of name then use the last index of
name then use the last index of method what is the last index of an O
method what is the last index of an O because index of gives you the first
because index of gives you the first index last gives you well the last
index last gives you well the last one what is the last index of O where is
one what is the last index of O where is it exactly
it exactly five 0 1 2 3 4 5
five 0 1 2 3 4 5 we can take a string and make all the
we can take a string and make all the characters uppercase all reassign that
characters uppercase all reassign that to our name variable so we're going to
to our name variable so we're going to take our name use the two uppercase
take our name use the two uppercase method then print our name after
method then print our name after reassigning
reassigning it now all the letters are
it now all the letters are uppercase there's also two
uppercase there's also two lowercase we'll replace upper with
lowercase we'll replace upper with lower and I should probably turn this
lower and I should probably turn this into a comment
into a comment now all the characters are
lowercase we can trim any white space before and after a string let's add a
before and after a string let's add a few spaces before and after then print
few spaces before and after then print the
the name we can eliminate all this white
name we can eliminate all this white space we'll use the trim method for that
space we'll use the trim method for that we'll reassign name equals name and use
we'll reassign name equals name and use the trim
method now while that white space is gone we can replace a character with
gone we can replace a character with another
another one name equals name we will replace one
one name equals name we will replace one character with another let's replace any
character with another let's replace any o's with A's for your own name feel free
o's with A's for your own name feel free to change
these so what is my name now
now broade there are methods that return
broade there are methods that return Boolean values to check to see if a
Boolean values to check to see if a string is empty you can use the is empty
string is empty you can use the is empty method this would return a Boolean to
method this would return a Boolean to demonstrate I'm going to put this within
demonstrate I'm going to put this within a print
statement so my string is not empty that's false but if it was it would
that's false but if it was it would return true but I have to turn these
return true but I have to turn these lines into
comments that would return true my name is empty this could be useful within an
is empty this could be useful within an if statement
if name do is empty method if our name is empty we will
method if our name is empty we will print your name is
print your name is empty else we will
print hello plus
hello plus name currently my name is
name currently my name is empty your name is
empty your name is empty this method returns true but if it
empty this method returns true but if it wasn't
wasn't it would return
it would return false hello whatever your name
is I'll use a multi-line comment just to comment all this
out we can check to see if our string contains a character that would return a
Boolean let's check to see if our name contains any spaces
true your name contains a
contains a space else will print your
space else will print your name doesn't
name doesn't contain any
contain any spaces so my name does contain a
spaces so my name does contain a space that would return true your name
space that would return true your name contains a
contains a space if we're working with let's say a
space if we're working with let's say a username usernames typically don't
username usernames typically don't contain
contain spaces your name doesn't contain any
spaces your name doesn't contain any spaces there is a method to check to see
spaces there is a method to check to see if two strings are
if two strings are equal again I'm going to use a
equal again I'm going to use a multi-line comment just to comment this
out if our name equals
name equals using the equals method we can check to
using the equals method we can check to see if two strings are equal the given
see if two strings are equal the given characters within them let's see if our
characters within them let's see if our name equals
password this actually would be more appropriate if we were working with the
appropriate if we were working with the string named password if our name if the
string named password if our name if the string of name is equal to this string
string of name is equal to this string if they have the same characters exactly
if they have the same characters exactly then we'll print your name can't be
then we'll print your name can't be password
else we will print
print hello plus
hello plus name I will set my name to be
password your name can't be password but if it
wasn't well then this returns false these two strings are not equal and we
these two strings are not equal and we execute the L statement hello your name
execute the L statement hello your name now the equals method doesn't account
now the equals method doesn't account for case sensitivity so let's say our
for case sensitivity so let's say our password has a capital
P well then this method returns false hello password to ignore case
hello password to ignore case sensitivity you can use equals ignore
sensitivity you can use equals ignore case then that would return true your
case then that would return true your name can't be password all right
name can't be password all right everybody those are a few useful string
everybody those are a few useful string Methods you may be interested in as a
Methods you may be interested in as a beginner using
beginner using Java all right everybody in this video
Java all right everybody in this video I'm going to explain how the substring
I'm going to explain how the substring method Works in Java substring is a
method Works in Java substring is a method that's used to extract a portion
method that's used to extract a portion of a string strings have a built-in
of a string strings have a built-in method of substring within the substring
method of substring within the substring method you can list one of two indices
method you can list one of two indices this method will create a new string
this method will create a new string based on the positioning of the indices
based on the positioning of the indices the start and the end I can best
the start and the end I can best demonstrate this with us creating an
demonstrate this with us creating an email SCE ER program so what we'll do in
email SCE ER program so what we'll do in this demonstration is create a string of
this demonstration is create a string of email type in your own email I don't
email type in your own email I don't want to give you guys my actual email
want to give you guys my actual email because some of you guys are weird no
because some of you guys are weird no offense my email will be bro1
offense my email will be bro1 23@gmail.com
our variable of email is a string strings have a built-in method of
strings have a built-in method of substring we can create a new string
substring we can create a new string from portions of the original string
from portions of the original string here's
here's how let's say I would like the first six
how let's say I would like the first six letters but depending on your own email
letters but depending on your own email it may be different the substring method
it may be different the substring method will return a new string so let's create
will return a new string so let's create a new variable the data type of string
a new variable the data type of string of usern
of usern name equals to create a substring we
name equals to create a substring we will take the original string use the
will take the original string use the substring
substring method then list one of two possible
method then list one of two possible indexes or indices the first index will
indexes or indices the first index will be zero at what position would we like
be zero at what position would we like this substring to end I would like to
this substring to end I would like to end right before this at sign so that
end right before this at sign so that would be 0 1 2 3 4 5
would be 0 1 2 3 4 5 6 the second index is exclusive so we're
6 the second index is exclusive so we're creating a new string of username by
creating a new string of username by using the substring method of our
using the substring method of our original string of email then let's
original string of email then let's print it to test it we will display our
print it to test it we will display our username and now we have a new string
username and now we have a new string mine is bro 1 123 but depending on what
mine is bro 1 123 but depending on what you wrote for your email it may be
you wrote for your email it may be different now I would like a new
different now I would like a new substring of every character after the
substring of every character after the at sign this will be a variable named
at sign this will be a variable named domain what is the domain of our email
domain what is the domain of our email again we're taking our original string
again we're taking our original string using the substring method then list one
using the substring method then list one of two possible indices so again let's
of two possible indices so again let's count this is index zero because in
count this is index zero because in programming we tend to start with zero 1
programming we tend to start with zero 1 2 3 4 5 6
7 so 7 8 9 10 11 12 13 14 15 16 then we will display our
domain so my domain is gmail.com within your substring method
gmail.com within your substring method if you have a starting index but you
if you have a starting index but you would like all the characters that come
would like all the characters that come after all the way till the end you don't
after all the way till the end you don't necessarily need an ending index X we
necessarily need an ending index X we could just say seven that would work too
could just say seven that would work too gmail.com there's one issue with how we
gmail.com there's one issue with how we wrote this program what if somebody has
wrote this program what if somebody has a different length of an email there's a
a different length of an email there's a greater or lesser number of characters
greater or lesser number of characters so let's say I have a different
email this program doesn't work as intended it's not flexible so my domain
intended it's not flexible so my domain is 1@gmail.com
is 1@gmail.com I could could modify the indices of the
I could could modify the indices of the substring method so 0 1 2 3 4 5 6
78 then the domain would be nine because I want everything after the at
sign and then my username let's check that so this would be my username bro
that so this would be my username bro code one to make this program more
code one to make this program more flexible instead of manually entering
flexible instead of manually entering the indices we can determine this number
the indices we can determine this number should be with another string method
should be with another string method we're going to use the index of method
we're going to use the index of method in place of a number we're going to find
in place of a number we're going to find the at character let's replace our
the at character let's replace our second
second index with email our string dot using
index with email our string dot using the index of method then we will find
the index of method then we will find the index of our at character we're
the index of our at character we're going to replace this number with email.
going to replace this number with email. index of and find the at sign so now
index of and find the at sign so now let's try printing our
let's try printing our username so here's my
username so here's my username then let's print the
domain currently we have that at sign the index of method returns a number
the index of method returns a number which we're using as the index it's
which we're using as the index it's returning the index of this at sign I'm
returning the index of this at sign I'm going to increase it by one so we get
going to increase it by one so we get everything after the at sign so plus
everything after the at sign so plus one and now the at sign is removed
one and now the at sign is removed even better yet let's accept some user
even better yet let's accept some user input we'll need a scanner import
input we'll need a scanner import java.util do scanner we'll create a
java.util do scanner we'll create a scanner
scanner object scanner scanner equals new
object scanner scanner equals new scanner then we will need
scanner then we will need system.in then when we open a scanner it
system.in then when we open a scanner it is a good idea to close it when we're
is a good idea to close it when we're done with it I sometimes forget
we'll create a prompt for a user to type in their
in their email enter your email I'll use print
email enter your email I'll use print instead of print line I'm going to
instead of print line I'm going to declare my variables after our scanner
declare my variables after our scanner that's just how I like to arrange things
that's just how I like to arrange things we'll declare our email but not yet
we'll declare our email but not yet assign
assign it same thing applies with our
it same thing applies with our username and our
username and our domain we've already declared these
domain we've already declared these variables we don't need to do that again
instead of manually assigning our email we're going to use our scanner to accept
we're going to use our scanner to accept user input scanner. nextt
user input scanner. nextt line let's display our username and our
domain okay enter your email I'll make up something bro1 123@gmail.com
up something bro1 123@gmail.com here's my username
here's my username and the
and the domain we can take this a step further
domain we can take this a step further too we can check to see if our email is
too we can check to see if our email is valid we'll use some of the string
valid we'll use some of the string Methods we learned about in the last
Methods we learned about in the last video so after accepting our email we're
video so after accepting our email we're going to write an if
going to write an if statement if our email contains the at
character our email is only valid if we have this at character if it is
have this at character if it is then we'll perform all this code so
then we'll perform all this code so let's cut it then stick it within the if
let's cut it then stick it within the if statement else we will do something
statement else we will do something else let's print emails must contain
else let's print emails must contain at let's type in an email that's not
at let's type in an email that's not valid I won't include the at
sign emails must contain the at character let's try that
character let's try that again fake
again fake guy one at maybe they're using Yahoo
guy one at maybe they're using Yahoo yahoo.com so my username would be fake
yahoo.com so my username would be fake guy one the domain is
guy one the domain is yahoo.com all right everybody so that is
yahoo.com all right everybody so that is the substring method and how to create
the substring method and how to create an email slicer program the substring
an email slicer program the substring method is used to extract a portion of a
method is used to extract a portion of a string you can list one of two possible
string you can list one of two possible indices within the substring method a
indices within the substring method a starting index and an ending index we
starting index and an ending index we use the substring method on an email
use the substring method on an email then created two new substrings one of
then created two new substrings one of username and the other of domain and
username and the other of domain and well everybody that is the substring
well everybody that is the substring method in
method in Java hey everybody in this video we're
Java hey everybody in this video we're going to create a weight conversion
going to create a weight conversion program to convert a weight from pounds
program to convert a weight from pounds to kilogram or vice versa it will help
to kilogram or vice versa it will help us become more familiar with if
us become more familiar with if statements so let's get started okay
statements so let's get started okay let's get started everybody what might
let's get started everybody what might be helpful to you as a beginner when
be helpful to you as a beginner when creating a project is to use comments to
creating a project is to use comments to describe what you want to do at each
describe what you want to do at each part of your program this is also known
part of your program this is also known as pseudo code for example the first
as pseudo code for example the first thing we'll do is declare our variables
thing we'll do is declare our variables declare
message then a prompt for user input prompt for user input or
Choice we'll say option one convert lbs meaning pounds to to kgs
one convert lbs meaning pounds to to kgs kilog option two convert kgs to
kilog option two convert kgs to LBS if somebody doesn't select option
LBS if somebody doesn't select option one or two we'll use an else statement
one or two we'll use an else statement else print not a valid
else print not a valid choice so here's a rough outline of our
choice so here's a rough outline of our program and what it's going to do we'll
program and what it's going to do we'll begin at the top we'll declare any
begin at the top we'll declare any variables that we'll need so we will
variables that we'll need so we will need a scanner we'll create a scanner
need a scanner we'll create a scanner object scanner scanner equals new
object scanner scanner equals new scanner then type system.in within set
scanner then type system.in within set of parentheses if you hover over the
of parentheses if you hover over the word scanner you can import it
word scanner you can import it automatically import
automatically import java.util.scanner or otherwise you can
java.util.scanner or otherwise you can type it
type it in what are some other variables we'll
in what are some other variables we'll need double weight for the original
need double weight for the original weight double new
weight double new weight that's after we convert the
weight that's after we convert the weight we'll need to store it and int
weight we'll need to store it and int choice
choice a user is going to type in one to
a user is going to type in one to convert pounds to kilograms or two to
convert pounds to kilograms or two to convert kilograms to
convert kilograms to pounds we have our variables now we need
pounds we have our variables now we need a welcome
a welcome message I'll use a few print
message I'll use a few print statements let's say weight
statements let's say weight conversion
program one C and space this means opt one convert lbs
space this means opt one convert lbs meaning pounds to kgs
meaning pounds to kgs kilog or Choice
kilog or Choice 2 to colon space convert kilogram to
2 to colon space convert kilogram to pounds
pounds lbs then we'll prompt for a user's
Choice I'll use print instead of print line choose an option
then we'll need to store that choice variable Choice equals use our scanner
variable Choice equals use our scanner to accept user input we're accepting an
to accept user input we're accepting an integer we'll use next
integer we'll use next int let's do a test run and I will print
int let's do a test run and I will print our choice
temporarily weight conversion program one to convert pounds to kilograms or
one to convert pounds to kilograms or two to convert kilograms to pounds I'll
two to convert kilograms to pounds I'll type in one we get one
type in one we get one or
or two then we output two we can delete
two then we output two we can delete this print line statement we were just
this print line statement we were just checking to see if it
checking to see if it works okay option one if somebody
works okay option one if somebody selects option one we have to convert
selects option one we have to convert pounds to
pounds to kilograms well we'll need to check to
kilograms well we'll need to check to see if choice is one we can use an if
see if choice is one we can use an if statement for
statement for that if choice is equal to one be sure
that if choice is equal to one be sure you use double equals that is the
you use double equals that is the comparison operator we're checking if
comparison operator we're checking if these two values are equal if you use a
these two values are equal if you use a single equals that is the assignment
single equals that is the assignment operator and Java thinks you're trying
operator and Java thinks you're trying to assign one to choice so double equals
to assign one to choice so double equals for
for comparisons we're converting pounds to
comparisons we're converting pounds to kilograms we'll ask a user to enter the
kilograms we'll ask a user to enter the weight in
weight in lbs I'll use print instead of print
line we we will assign our weight equals use our scanner then use
weight equals use our scanner then use the next Double method then we will
the next Double method then we will accept a double value so once we have
accept a double value so once we have our weight we have to convert it to
our weight we have to convert it to kilograms because it's currently in
kilograms because it's currently in pounds we will assign our new weight
pounds we will assign our new weight equal to the weight our current weight
equal to the weight our current weight that
that is times
is times 0.45 3592
weight the new weight in
new weight in kgs
kgs is then we'll add our new
is then we'll add our new weight okay let's perform a test
weight okay let's perform a test run we'll type in one to convert pounds
run we'll type in one to convert pounds to kilogram enter the weight in pounds
to kilogram enter the weight in pounds what's 150 lb converted to kilog
what's 150 lb converted to kilog 68.0
68.0 388 if you would like to limit the
388 if you would like to limit the amount of digits that display after the
amount of digits that display after the decimal you can use a print F statement
decimal you can use a print F statement instead of print line so to do that
instead of print line so to do that we'll convert this to print
we'll convert this to print F where we would like to insert a value
F where we would like to insert a value or variable we'll use percent since
or variable we'll use percent since we're displaying a double we'll use f
we're displaying a double we'll use f meaning floating Point number to display
meaning floating Point number to display two digits after the decimal we'll use 0
two digits after the decimal we'll use 0 2 or 0.1 to display one digit depending
2 or 0.1 to display one digit depending on your preference replace the plus with
on your preference replace the plus with a
a comma we're inserting this variable at
comma we're inserting this variable at this location this placeholder let's
this location this placeholder let's perform that
perform that again choose an option convert pounds to
again choose an option convert pounds to kilograms enter the weight in pounds 150
kilograms enter the weight in pounds 150 is good the new weight in kilogram is
is good the new weight in kilogram is 68.4
68.4 kilg now if Choice equals 2 we're going
kilg now if Choice equals 2 we're going to convert kilog to pounds and really we
to convert kilog to pounds and really we can just copy the if statement paste it
can just copy the if statement paste it then convert
then convert it else if Choice equals 2 the user
it else if Choice equals 2 the user wants to convert kilogram to pounds
wants to convert kilogram to pounds enter the weight in
enter the weight in kilog the new formula is going to be
kilog the new formula is going to be weight time
weight time 2.24
2.24 62 the new weight in pounds lbs is our
62 the new weight in pounds lbs is our new
new weight let's try
weight let's try it choose an option we will convert
it choose an option we will convert kilograms to pounds I'm going to press
kilograms to pounds I'm going to press two enter the weight in kilogram let's
two enter the weight in kilogram let's say 68
say 68 kg the new weight in pounds is
kg the new weight in pounds is 14991
14991 lb what if somebody types in a number
lb what if somebody types in a number that's not
that's not valid so we can get rid of this comment
valid so we can get rid of this comment is use an else statement to print print
is use an else statement to print print that the user didn't select a valid
that the user didn't select a valid choice we will follow this with an lse
choice we will follow this with an lse statement we will follow else if with an
statement we will follow else if with an else statement else
else statement else print that was not a valid
choice we have options one or two if I type in three we execute the L statement
type in three we execute the L statement that was not a valid
that was not a valid choice and again like usual I'm
choice and again like usual I'm forgetting to close my scanner because I
forgetting to close my scanner because I sometimes forget to do that so at the
sometimes forget to do that so at the end of your program close your scanner
end of your program close your scanner scanner. close because you don't want to
scanner. close because you don't want to leave resources
leave resources open okay let's do one final test run
open okay let's do one final test run let's convert pounds to kilograms what's
let's convert pounds to kilograms what's 200 lb converted to
200 lb converted to kilograms 90.7
kilograms 90.7 2 all right everybody so that is a
2 all right everybody so that is a weight conversion program you can write
weight conversion program you can write using
using [Music]
[Music] Java hey everybody in this video I'm
Java hey everybody in this video I'm going to show you how we can use the
going to show you how we can use the tary operator in Java in Java the tary
tary operator in Java in Java the tary operator is a question mark followed by
operator is a question mark followed by one of two possible values here's the
one of two possible values here's the formula we check a condition then use a
formula we check a condition then use a question mark like we're asking a
question mark like we're asking a question is this condition true if it is
question is this condition true if it is we'll return a value if not we return
we'll return a value if not we return something else a different value it's a
something else a different value it's a simpler version to an if else statement
simpler version to an if else statement here's a
here's a demonstration let's say we have an
demonstration let's say we have an integer of a score score will equal 70
integer of a score score will equal 70 that's technically
that's technically passing using an if statement I will
passing using an if statement I will check if my score is greater than or
check if my score is greater than or equal to
60 if it is then we will print pass else we will
print fail so this does work with a score of 70 I have passed if
work with a score of 70 I have passed if it were 55
it were 55 well then I fail there's another way in
well then I fail there's another way in which we can write this and that is by
which we can write this and that is by using the tary
using the tary operator what we're going to do let's
operator what we're going to do let's create a variable a string variable of
create a variable a string variable of pass or
pass or fail and we're basically just following
fail and we're basically just following this formula we have our condition is
this formula we have our condition is our score greater than or equal to
our score greater than or equal to 60 question mark we're asking a question
60 question mark we're asking a question is this condition true if it is let's
is this condition true if it is let's return a string of pass colon think of
return a string of pass colon think of it like
it like otherwise will return
otherwise will return fail and then I will print pass or fail
fail and then I will print pass or fail to display it so 55 that means we fail
to display it so 55 that means we fail but if it were
but if it were 75 that means we pass by using the tary
75 that means we pass by using the tary operator it's an alternative to writing
operator it's an alternative to writing an if else statement and it can be
an if else statement and it can be simpler in many cases here's a few other
simpler in many cases here's a few other examples let's create a variable of
examples let's create a variable of number set it equal to some
number set it equal to some number using the Turner operator we will
number using the Turner operator we will check if this number is even or
check if this number is even or odd I'll create a string of even or odd
odd I'll create a string of even or odd equals our
equals our condition we can check if a number is
condition we can check if a number is even or odd by using the modulus
even or odd by using the modulus operator
operator we will take our
we will take our number modulus 2 the modulus operator
number modulus 2 the modulus operator gives you the remainder of any division
gives you the remainder of any division does 3 divide by two evenly if it does
does 3 divide by two evenly if it does that would equal
zero 3 doesn't divide by two evenly there's a remainder of one and that does
there's a remainder of one and that does not equal
not equal zero is this number divisible by two
zero is this number divisible by two we'll use the trary operator if it is
we'll use the trary operator if it is we'll return a string of even otherwise
we'll return a string of even otherwise we'll return a string of odd is my
we'll return a string of odd is my number even or
number even or odd so three is
odd so three is odd but if it were
odd but if it were four well then it's
four well then it's even here's a more practical example
even here's a more practical example let's say we're working with a
let's say we're working with a time in hours this will be in military
time in hours this will be in military time hours equals
time hours equals 13 that would be the the same as 1
13 that would be the the same as 1 p.m. I will create a string of time of
p.m. I will create a string of time of day equals we'll check if our hours is
day equals we'll check if our hours is greater than or equal to 12 if it is
greater than or equal to 12 if it is we'll return PM if not will return
we'll return PM if not will return am hours less than
am hours less than 12 tary operator is our hours less than
12 tary operator is our hours less than 12 if it is we'll return a.m.
12 if it is we'll return a.m. otherwise will return
otherwise will return p.m and then we will display the time of
p.m and then we will display the time of day 13 hours that's the same as 1:
day 13 hours that's the same as 1: p.m. yep the time is 1: p.m. or if the
p.m. yep the time is 1: p.m. or if the hours were 9 that would be
hours were 9 that would be am all right last example let's say we
am all right last example let's say we have an income or
have an income or salary income equals $60,000
let's pretend that you're a software engineer in the united states in the
engineer in the united states in the United States we have different tax
United States we have different tax brackets depending on your income this
brackets depending on your income this time we will assign a variable of tax
time we will assign a variable of tax rate equals we'll check if our
rate equals we'll check if our income is greater than or equal
income is greater than or equal to $40,000 for
$40,000 question mark turnar operator if that's true then our tax
operator if that's true then our tax rate is going to be
rate is going to be 0.25 otherwise it will be
0.15 so with our income what is the tax rate
rate 0.25 but if I changed it to
0.25 but if I changed it to 30,000 well then our tax rate would be
30,000 well then our tax rate would be 0.15 for
0.15 for 15% so that is the tary operator you
15% so that is the tary operator you follow this formula you check a
follow this formula you check a condition within a set of parentheses
condition within a set of parentheses then use the tary operator like you're
then use the tary operator like you're asking a question if this condition is
asking a question if this condition is true return this otherwise if it's false
true return this otherwise if it's false return something else and then if you
return something else and then if you would like you can assign it to a
would like you can assign it to a variable and well everybody that is the
variable and well everybody that is the tary operator in
Java all right everybody in this video we're going to create a temperature
we're going to create a temperature conversion program to convert from
conversion program to convert from Celsius to Fahrenheit or Fahrenheit to
Celsius to Fahrenheit or Fahrenheit to Celsius this is a practice project to
Celsius this is a practice project to get us more familiar using the tary
get us more familiar using the tary operator so let's get started we will be
operator so let's get started we will be accepting some user input so let's get
accepting some user input so let's get the scanner out of the way first scanner
the scanner out of the way first scanner scanner equals new scanner we need a
scanner equals new scanner we need a scanner to accept user input within the
scanner to accept user input within the set of parentheses type
set of parentheses type system.in and then I will just
system.in and then I will just automatically import this class so at
automatically import this class so at the top of your Java file you need this
the top of your Java file you need this import import
import import java.util.scanner then when you open a
java.util.scanner then when you open a scanner it is a good idea to close it at
scanner it is a good idea to close it at the end of your file when you're done
the end of your file when you're done with it because you don't want to leave
with it because you don't want to leave resources open we have our scanner to
resources open we have our scanner to accept user input let's declare some
accept user input let's declare some variables what will we need we will need
variables what will we need we will need the original temperature this will be of
the original temperature this will be of the double data type double temp we'll
the double data type double temp we'll need a new temperature let's say double
need a new temperature let's say double new temp that's after we convert it and
new temp that's after we convert it and a unit we could use Char for the unit
a unit we could use Char for the unit you know the letter F or c for
you know the letter F or c for Fahrenheit or Celsius but just to keep
Fahrenheit or Celsius but just to keep it simple I'm going to use a string
it simple I'm going to use a string because there's a built-in method of two
because there's a built-in method of two uppercase we can take the input and make
uppercase we can take the input and make it uppercase automatically just to make
it uppercase automatically just to make it simple we'll use a string rather than
it simple we'll use a string rather than a Char for the
a Char for the unit okay now we just need to get the
unit okay now we just need to get the temperature we'll need a prompt I'll use
temperature we'll need a prompt I'll use print instead of print line we will ask
print instead of print line we will ask the user to enter the
temperature we will assign the temperature temp equals scanner. next
temperature temp equals scanner. next Double because we're accepting a value
Double because we're accepting a value we're signing a variable of the double
we're signing a variable of the double data type now we need the unit is it
data type now we need the unit is it going to be Celsius or
going to be Celsius or Fahrenheit we'll need another prompt
Fahrenheit we'll need another prompt I'll use print instead of print
I'll use print instead of print line we will ask the user convert to
line we will ask the user convert to Celsius or Fahrenheit
F let's ass our unit variable use our
variable use our scanner then use the next method to get
scanner then use the next method to get the next character we'll use the next
the next character we'll use the next method to get the next
method to get the next character we don't necessarily need next
character we don't necessarily need next line we just want a single
line we just want a single character so check this out I'm going to
character so check this out I'm going to Output our temp
Output our temp and our
unit what if somebody types in a lowercase C or F so let's say the
lowercase C or F so let's say the temperature is
temperature is 75 75° F and we would like to convert it
75 75° F and we would like to convert it to Celsius I'll type lowercase C rather
to Celsius I'll type lowercase C rather than uppercase
C our unit is currently a lowercase C we can convert it to be
can convert it to be uppercase following the next method of
uppercase following the next method of our scanner where we assign our unit
our scanner where we assign our unit we're going to do something called
we're going to do something called method
method chaining we'll add another dot then use
chaining we'll add another dot then use the two uppercase method of
the two uppercase method of strings let's try that again and see if
strings let's try that again and see if it
it works
works 75 I'll type in lower case
C the two uppercase method will take that lowercase C and make it uppercase
that lowercase C and make it uppercase which is what we'll need in this next
which is what we'll need in this next section we can delete these two
section we can delete these two statements now we're going to use the
statements now we're going to use the tary
tary operator how the trary operator works is
operator how the trary operator works is that we check a
that we check a condition followed by a question mark
condition followed by a question mark like we're asking a question we will
like we're asking a question we will return some code if that condition is
return some code if that condition is true colon meaning else if it's false
true colon meaning else if it's false we'll do some other code or return some
we'll do some other code or return some other value we're going to follow this
other value we're going to follow this formula so what is our condition let's
formula so what is our condition let's check to see if our unit is equal to a c
check to see if our unit is equal to a c take our variable of
take our variable of unit use the equals method because
unit use the equals method because strings have a built-in method of
strings have a built-in method of equals does our unit equal in uppercase
equals does our unit equal in uppercase C question mark That's the tary operator
C question mark That's the tary operator we're asking a
we're asking a question if this is true that means
question if this is true that means we're trying to convert from Fahrenheit
we're trying to convert from Fahrenheit to Celsius
to Celsius the formula to do that would be the
the formula to do that would be the following we would be executing this
following we would be executing this code since it's
code since it's true take our temp subtract
true take our temp subtract 32 then multiply 5 /
32 then multiply 5 / 9 now what if our unit does not equal C
9 now what if our unit does not equal C that means we're trying to convert to
that means we're trying to convert to Fahrenheit we'll need that colon for the
Fahrenheit we'll need that colon for the next part of the
next part of the section now here's the formula to
section now here's the formula to convert from Celsius to Fahrenheit
convert from Celsius to Fahrenheit this will be the false section of the
this will be the false section of the trinary
trinary operator take our temp * 5 /
operator take our temp * 5 / 9 +
9 + 32 with the trinary operator how we've
32 with the trinary operator how we've written this code is that we're going to
written this code is that we're going to be returning a double after converting
be returning a double after converting it we need to do something with it so
it we need to do something with it so we're going to assign it to a variable
we're going to assign it to a variable our variable of new temp then we can do
our variable of new temp then we can do something with it
something with it once we have our new temperature let's
once we have our new temperature let's display it I'll perform a test run let's
display it I'll perform a test run let's print our new
print our new temp let's say it's 100° F and we're
temp let's say it's 100° F and we're going to convert to Celsius I'll type in
going to convert to Celsius I'll type in see well the temperature in Celsius is
see well the temperature in Celsius is 37.7 repeating we're going to format
37.7 repeating we're going to format this in a
this in a moment let's add a degree
moment let's add a degree symbol plus a string on Windows to add a
symbol plus a string on Windows to add a degree symbol make sure num lock is on
degree symbol make sure num lock is on hold alt then type
0176 plus our unit we're converting to let's try that
let's try that again what is 100° fah converted to
again what is 100° fah converted to Celsius
Celsius 37.7 repeating de
37.7 repeating de C to limit the amount of digits that
C to limit the amount of digits that display after the decimal we we can use
display after the decimal we we can use a print F statement let's convert our
a print F statement let's convert our print line for the new temp to be print
print line for the new temp to be print F rather than print
F rather than print line we'll add a
placeholder we're displaying a double so we need F to display one digit type 0.1
we need F to display one digit type 0.1 between the percent sign and the
between the percent sign and the F comma new
temp after our placeholder We'll add our degree symbol again I'm holding alt numb
degree symbol again I'm holding alt numb lock is on I'm typing
lock is on I'm typing 0176 then we will display the unit it's
0176 then we will display the unit it's a string percent s for
a string percent s for Strings we're inserting a new variable
Strings we're inserting a new variable we're going to comma separate them then
we're going to comma separate them then add our
add our unit and let me just close this Gap
unit and let me just close this Gap let's see what the final product
let's see what the final product is let's convert
is let's convert 30.1 this will be in Celsius to
30.1 this will be in Celsius to Fahrenheit
Fahrenheit and the temperature in Fahrenheit is
and the temperature in Fahrenheit is 48.7 De
48.7 De fahit okay everybody that is a
fahit okay everybody that is a temperature conversion program that you
temperature conversion program that you can write using the tary operator in
Java why hello there today I got to explain something called enhanced
explain something called enhanced switches in Java in Java there switches
switches in Java in Java there switches and then there's enhanced switches
and then there's enhanced switches enhanced switches are a Java 14 feature
enhanced switches are a Java 14 feature I would recommend using using enhanced
I would recommend using using enhanced switches over standard switches so what
switches over standard switches so what is a switch exactly a switch is a
is a switch exactly a switch is a replacement to using many l statements
replacement to using many l statements here's an example of us using a lot of
here's an example of us using a lot of lse if statements in this sample program
lse if statements in this sample program we have a day of the week I set mine to
we have a day of the week I set mine to be Friday with each of these if
be Friday with each of these if statements I am checking to see if the
statements I am checking to see if the day equals Monday Tuesday so on and so
day equals Monday Tuesday so on and so forth currently my day is set to
forth currently my day is set to Friday this would give me it is a
Friday this would give me it is a weekday
weekday if I set the day to be
if I set the day to be Saturday well then it is the
Saturday well then it is the weekend or Sunday let me show you the
weekend or Sunday let me show you the code it is the weekend then I have an
code it is the weekend then I have an else statement if none of the above
else statement if none of the above conditions are true for example let's
conditions are true for example let's say day is pizza day which doesn't exist
say day is pizza day which doesn't exist but it really
but it really should Pizza day is not a day this code
should Pizza day is not a day this code does work but it could be more efficient
does work but it could be more efficient we have a lot of redundancies we're
we have a lot of redundancies we're using a lot of else if statements that
using a lot of else if statements that all basically do the same
thing an improvement would be to use an enhanced switch let me demonstrate how
enhanced switch let me demonstrate how to make
to make that so let's set our day to be Monday
that so let's set our day to be Monday for example to create a switch we will
for example to create a switch we will type switch at a set of parentheses then
type switch at a set of parentheses then a set of curly
a set of curly braces it's similar to an if statement
braces it's similar to an if statement already with within the set of
already with within the set of parentheses for the switch we're going
parentheses for the switch we're going to examine a value or variable we're
to examine a value or variable we're going to examine our string of day we
going to examine our string of day we will examine this value against any
will examine this value against any matching cases the first case will be a
matching cases the first case will be a string of
string of Monday if day is equal to this value a
Monday if day is equal to this value a string of Monday we'll do
string of Monday we'll do something we'll use an arrow an arrow is
something we'll use an arrow an arrow is the arrow operator in Java think of it
the arrow operator in Java think of it as meaning do something do this if day
as meaning do something do this if day equals Monday do this code so let's
equals Monday do this code so let's print
print something let's print it is a
something let's print it is a weekday and then for fun you don't have
weekday and then for fun you don't have to but I'm going to add an
to but I'm going to add an emoji nobody likes Mondays let's be
emoji nobody likes Mondays let's be honest if day is Monday do this code
honest if day is Monday do this code let's add another case let me zoom in a
let's add another case let me zoom in a little if Case is
little if Case is Tuesday Arrow op operator meaning do
Tuesday Arrow op operator meaning do this code we will print we'll print the
this code we will print we'll print the same thing it is a
same thing it is a weekday we'll do this with the other
weekday we'll do this with the other days too I'll just copy this code then
days too I'll just copy this code then repurpose it to save some time case
repurpose it to save some time case Wednesday it is a
Wednesday it is a weekday case
weekday case Thursday it is a
Thursday it is a weekday case
weekday case Friday it is a weekday now if it's sat
Friday it is a weekday now if it's sat Saturday that means it's the
Saturday that means it's the weekend case
weekend case Saturday it is the weekend let's change
Saturday it is the weekend let's change the
weekend let's perform a test run if you're using intellig you may have These
you're using intellig you may have These Warnings it's basically saying that
Warnings it's basically saying that these sections of code are unreachable
these sections of code are unreachable we're manually setting a variable these
we're manually setting a variable these sections of code are not going to
sections of code are not going to execute so I would just ignore that for
execute so I would just ignore that for now so let's perform a test
now so let's perform a test run my day is Monday day is equal to the
run my day is Monday day is equal to the case of Monday so we do this code if it
case of Monday so we do this code if it were
Friday case Friday we do this code if Case were Saturday
well we do this code and
Sunday case Sunday so we do this code it is the
is the weekend what if we have a day that
weekend what if we have a day that doesn't exist like pizza
day well we can add a default case here's how we'll type the keyword
here's how we'll type the keyword default Arrow meaning do
default Arrow meaning do this we'll print
this we'll print our variable
our variable day plus a string of is not a
day Pizza day is not a day the default case it behaves similarly to your else
case it behaves similarly to your else statement if no above conditions are
statement if no above conditions are true then we will do
true then we will do this so what we'll do now is accept some
this so what we'll do now is accept some user input using a scanner we'll need to
user input using a scanner we'll need to create a scanner object scanner scanner
create a scanner object scanner scanner equals new scanner within the set of
equals new scanner within the set of parentheses type
parentheses type system.in and then I'm just going to
system.in and then I'm just going to automatically import this class at the
automatically import this class at the top of my Java file import
top of my Java file import java.util.scanner
java.util.scanner we'll create a prompt for a user to type
we'll create a prompt for a user to type in the
in the day enter the day of the week and I will
day enter the day of the week and I will use print instead of print line instead
use print instead of print line instead of manually assigning a variable we'll
of manually assigning a variable we'll use our scanner scanner. nextt line to
use our scanner scanner. nextt line to accept a
string okay let's try this again enter the day of the week it is
again enter the day of the week it is Tuesday it is a weekday let's try that
Tuesday it is a weekday let's try that again enter the day of the week it is
again enter the day of the week it is Saturday it is the
Saturday it is the weekend and let's make up a
weekend and let's make up a day uh let's go with taco
day uh let's go with taco day taco day is not a
day taco day is not a day we could actually improve this widg
day we could actually improve this widg even further intellig is saying we have
even further intellig is saying we have a duplicate branch in our switch we have
a duplicate branch in our switch we have two or more cases that are doing the
two or more cases that are doing the same thing we are outputting it is a
weekday we could consolidate some of these cases here's how the cases of
these cases here's how the cases of Monday Tuesday Wednesday Thursday and
Monday Tuesday Wednesday Thursday and Friday they all output the same thing so
Friday they all output the same thing so we're going to consolidate them I'll
we're going to consolidate them I'll copy one of these print statements and
copy one of these print statements and delete all of them
we can comma separate these cases so case Monday
case Monday comma
comma Tuesday
Tuesday comma
comma Wednesday
Wednesday comma
comma Thursday
Thursday comma
comma Friday then Arrow
Friday then Arrow if our case is Monday Tuesday Wednesday
if our case is Monday Tuesday Wednesday Thursday or Friday then do the following
Thursday or Friday then do the following we'll print it is a
we'll print it is a weekday now Saturday and Sunday do the
weekday now Saturday and Sunday do the same thing
same thing too let's cut one of these
too let's cut one of these lines and delete
lines and delete them case
them case Saturday comma
Saturday comma Sunday Arrow meaning do this it is the
Sunday Arrow meaning do this it is the weekend then we'll keep keep our default
weekend then we'll keep keep our default case in case there are no matches let's
case in case there are no matches let's try this
try this again enter the day of the week it is
again enter the day of the week it is Wednesday it is a
Wednesday it is a weekday it is
weekday it is Saturday it is the
Saturday it is the weekend it is Sunday it is the
weekend uh then let's go with uh Hamburger
Hamburger Day hamburger day is not a day
Day hamburger day is not a day so those are enhanced switches they're a
so those are enhanced switches they're a replacement to using many LF
replacement to using many LF statements if you find yourself using a
statements if you find yourself using a lot of lsif statements I would recommend
lot of lsif statements I would recommend using a switch instead but not just any
using a switch instead but not just any switch an enhanced switch which is a
switch an enhanced switch which is a Java 14 feature that you should know
Java 14 feature that you should know about and well everybody those are
about and well everybody those are enhanced switches in
Java what is going on everybody in this video we're going to create a simple
video we're going to create a simple calculator program using what we've
calculator program using what we've learned with enhanced switches this is
learned with enhanced switches this is meant to be more of a practice project
meant to be more of a practice project let's get started the first thing we'll
let's get started the first thing we'll need is a scanner we will create a
need is a scanner we will create a scanner object scanner scanner equals
scanner object scanner scanner equals new scanner within the set of
new scanner within the set of parentheses type
parentheses type system.in and then when you open a
system.in and then when you open a scanner it is a good idea to close it
scanner it is a good idea to close it when you're done with
when you're done with it scanner. close then be sure to import
it scanner. close then be sure to import the class at the top of your Java file
the class at the top of your Java file make sure you have this import import
make sure you have this import import java.util.scanner
java.util.scanner what are the different variables we'll
what are the different variables we'll need a user is going to type in two
need a user is going to type in two numbers and an operator such as a plus
numbers and an operator such as a plus for addition minus for subtraction so on
for addition minus for subtraction so on and so forth the first variable will be
and so forth the first variable will be up the double data type double num
up the double data type double num one double num two then an operator this
one double num two then an operator this will be a Char Char operator
will be a Char Char operator and a result double
result there's going to be one more variable but we'll fill that in later so
variable but we'll fill that in later so we'll stick with these four for now
we'll stick with these four for now we'll prompt a user to type in the first
we'll prompt a user to type in the first number followed by an operator than the
number followed by an operator than the second
second number here's how we can write
number here's how we can write that let's ask the user to enter the
that let's ask the user to enter the first number and I will use print
first number and I will use print instead of print line
we will assign num one equal to use our scanner to get user
scanner to get user input next
Double then we need the operator we will use a print
use a print statement enter n
statement enter n operator we'll have Plus for addition
operator we'll have Plus for addition minus for subtraction an asterisk for
minus for subtraction an asterisk for multiplication a for slash for division
multiplication a for slash for division let's add one more let's add a carrot
let's add one more let's add a carrot this will raise a base to a given
this will raise a base to a given power feel free to add more if you would
power feel free to add more if you would like but we'll just stick with these
like but we'll just stick with these five a user is going to enter in a
five a user is going to enter in a character one of these operators
character one of these operators hopefully we will assign our variable of
hopefully we will assign our variable of operator equal to
operator equal to scanner.
next the next method will give you a string we can method chain the Char at
string we can method chain the Char at method to return a single character when
method to return a single character when a user types in something just give me
a user types in something just give me the first character this will also
the first character this will also convert it to be a character rather than
convert it to be a character rather than keep it a
keep it a string so ideally our operator is going
string so ideally our operator is going to be a plus a minus an asterisk a
to be a plus a minus an asterisk a forward slash or a
forward slash or a carrot then we need num two we can just
carrot then we need num two we can just copy these two lines paste them change
copy these two lines paste them change first to be second and num one to be num
first to be second and num one to be num two we have our two numbers and our
two we have our two numbers and our operator we have to determine what the
operator we have to determine what the operator is we can use an enhanced
operator is we can use an enhanced switch for that we will create a
switch for that we will create a switch within the set of
switch within the set of parentheses we are examining our
parentheses we are examining our operator we're examining our operator
operator we're examining our operator against any matching cases the first
against any matching cases the first case will be a plus sign and these cases
case will be a plus sign and these cases are going to be within single quotes not
are going to be within single quotes not double quotes because we're working with
double quotes because we're working with a character not a
a character not a string with our switch if our operator
string with our switch if our operator is a plus character we're going to write
is a plus character we're going to write an arrow meaning do
an arrow meaning do this we will take our variable of
this we will take our variable of result set it equal to be num one that's
result set it equal to be num one that's the first number plus num two
the first number plus num two that will be the case for addition then
that will be the case for addition then we have
we have subtraction case minus Arrow do this
subtraction case minus Arrow do this assign our result equal to num one minus
assign our result equal to num one minus num
num 2 multiplication would be
2 multiplication would be case a character vaster risk arrow take
case a character vaster risk arrow take our result equals num one * num
two now for division we have a forward
we have a forward slash arrow take our result equals num
slash arrow take our result equals num one divided by num
one divided by num two now with division if somebody
two now with division if somebody divides by zero we'll return to this
divides by zero we'll return to this case later and make it a little more
case later and make it a little more sophisticated where we check to see if
sophisticated where we check to see if num 2 is zero I would like for us to get
num 2 is zero I would like for us to get a solid foundation first for this
a solid foundation first for this program so if somebody would like to
program so if somebody would like to raise a base to a given power we will
raise a base to a given power we will use the
carrot we will assign our result equal to now we're going to use the math
to now we're going to use the math class the power method of the math class
class the power method of the math class we can raise a base to a given power we
we can raise a base to a given power we will raise num one to the power of num
two let's perform a test run just to be sure that it
sure that it works I'm going to display our result
works I'm going to display our result after the
after the switch so Java is giving us a warning
switch so Java is giving us a warning that variable result might not have been
that variable result might not have been initialized that's because it's possible
initialized that's because it's possible there's no matching
there's no matching cases and we would be keeping our result
cases and we would be keeping our result uninitialized so to clear that up when
uninitialized so to clear that up when we declare our variable we can also
we declare our variable we can also assign it I'll just set it to be
assign it I'll just set it to be zero let's perform a test
run enter the first number let's do 3.14 enter an operator let's do addition
3.14 enter an operator let's do addition and the second number
and the second number 1.1 the result is
1.1 the result is 4.24 let's do subtraction
4.24 let's do subtraction 3.14 minus 1.1 which gives us
3.14 minus 1.1 which gives us 2.04
2.04 multiplication
multiplication 3.14 times let's do
3.14 times let's do two
divided by two that gives us
two that gives us 1.57 then we have power what is
1.57 then we have power what is 3 to the power of
3 to the power of three that is
three that is 27 3 * 3 is 9 * 3 is 27 3 ^ of
27 3 * 3 is 9 * 3 is 27 3 ^ of 3 we have one potential issue though
3 we have one potential issue though what if somebody divides by zero here's
what if somebody divides by zero here's what happens
what happens what is
what is 3.14 /
3.14 / 0 we get the output of
0 we get the output of infinity here's how we could prevent
infinity here's how we could prevent that underneath the case where we do
that underneath the case where we do division we'll write a few lines rather
division we'll write a few lines rather than just one but we're going to enclose
than just one but we're going to enclose them within a set of curly
them within a set of curly braces then I'm going to cut this line
braces then I'm going to cut this line of
of code within this case we'll write an if
code within this case we'll write an if statement we'll
statement we'll check
check if num 2 is equal to
if num 2 is equal to zero that's because we can't normally
zero that's because we can't normally divide by zero if it is then let's print
divide by zero if it is then let's print cannot divide by
zero else we'll assign our result of num one
else we'll assign our result of num one / by num 2 we'll execute the L statement
/ by num 2 we'll execute the L statement if num 2 doesn't equal zero because if
if num 2 doesn't equal zero because if it did this would be true and we execute
it did this would be true and we execute this code instead let's try that
this code instead let's try that again what is
again what is 3.14 /
3.14 / 0 cannot divide by
0 cannot divide by zero however we still do display a
zero however we still do display a result and that is by using this print
result and that is by using this print statement what if somebody types in an
statement what if somebody types in an operator that doesn't exist 3.14
operator that doesn't exist 3.14 I'm going to type in pizza for the
I'm going to type in pizza for the operator type in I don't know
operator type in I don't know one well we still display a result so
one well we still display a result so let's modify this program let's display
let's modify this program let's display a result only if we have a valid
a result only if we have a valid operator because right now we don't
operator because right now we don't Pizza is not a valid
operator let's add a Boolean variable of valid
valid operation I will set this to be true
operation I will set this to be true from the
beginning if somebody attempts to divide by zero I'm going to take our valid
by zero I'm going to take our valid operation variable and set it to be
operation variable and set it to be false because we do not want to continue
false because we do not want to continue and display the
result we're going to add a default case the default case will be the
following so I'm going to write two lines of code for the default
lines of code for the default case let's
case let's output invalid
operator then we will take our Boolean variable of valid operation and set it
variable of valid operation and set it to be
to be false so this is what our switch looks
false so this is what our switch looks like feel free to pause the video if you
like feel free to pause the video if you would like a moment to look it
would like a moment to look it over within our case of division we do
over within our case of division we do have a few lines of code same thing
have a few lines of code same thing applies with the default
applies with the default case we're only going to print the
case we're only going to print the result if our Boolean of valid operation
result if our Boolean of valid operation is
is true if valid operation is equal to true
true if valid operation is equal to true but really we can just shorten this to
but really we can just shorten this to if valid
if valid operation then we'll print the
operation then we'll print the result then we don't necessarily need an
result then we don't necessarily need an else
else statement because we're already printing
statement because we're already printing either invalid operator or cannot divide
either invalid operator or cannot divide by zero
by zero okay let's run this one final
okay let's run this one final time
time 3.14 plus
3.14 plus 2.1 is
2.1 is 5.24
5.24 3.14
3.14 minus 1.1 is
3.14 time 2.1 is 6594
2.1 is 6594 4
4 3.14 okay 3.14 / 0 Let's see what
3.14 okay 3.14 / 0 Let's see what happens cannot divide by zero and we do
happens cannot divide by zero and we do not display the result because our
not display the result because our equation is invalid which is good we
equation is invalid which is good we don't want to display the result we're
don't want to display the result we're displaying a type of error message
instead let's raise 4 to the
4 to the power of two which gives us
power of two which gives us 16 now let's type in an operator that
16 now let's type in an operator that doesn't exist
3.14 Pizza
Pizza 69 invalid operator that's because Pizza
69 invalid operator that's because Pizza is not a valid
is not a valid operator all right everybody that is a
operator all right everybody that is a calculator program that you can write
calculator program that you can write the purpose of this program is to more
the purpose of this program is to more or less help us with enhanced switch
or less help us with enhanced switch statements depending on the operator we
statements depending on the operator we can perform one of a few operations
can perform one of a few operations we've also learned that your cases can
we've also learned that your cases can take up more than one line if you would
take up more than one line if you would like and well everybody that is a
like and well everybody that is a calculator program in
Java yo yo yo in today's video I'm going to explain logical operators in Java
to explain logical operators in Java logical operators they allow us to check
logical operators they allow us to check or modify more than one condition
or modify more than one condition there's and or not we'll discuss and
there's and or not we'll discuss and first which is represented by two Amper
first which is represented by two Amper Sands let's declare a variable of
Sands let's declare a variable of temperature temp meaning temperature I
temperature temp meaning temperature I will set this to be 20 I would like to
will set this to be 20 I would like to check to see if my temperature Falls
check to see if my temperature Falls within a certain range well to do that I
within a certain range well to do that I could use the and logical operator we
could use the and logical operator we can check more than one
can check more than one condition so first I would like to see
condition so first I would like to see if my
if my temp is less than or equal to 30 30°
temp is less than or equal to 30 30° C and if the temp is greater than or
C and if the temp is greater than or equal to zero
equal to zero we have two conditions this time if this
we have two conditions this time if this is true and this is true then do this
is true and this is true then do this code so let's output the
code so let's output the following if our temperature Falls
following if our temperature Falls within this range we'll
within this range we'll output the weather is good and for fun
output the weather is good and for fun I'll let a smiley face cuz why not okay
I'll let a smiley face cuz why not okay let's see how this works the temperature
let's see how this works the temperature is currently 20 20° C
is currently 20 20° C the weather is good if the temperature
the weather is good if the temperature were 40 40°
were 40 40° C well we don't do
C well we don't do anything this condition evaluated to be
anything this condition evaluated to be false but this one is true our
false but this one is true our temperature is greater than or equal to
temperature is greater than or equal to zero that is true but this one is false
zero that is true but this one is false and using the and logical operator both
and using the and logical operator both conditions must be true in order for
conditions must be true in order for this entire statement to be true
this entire statement to be true since only one of them was true where
since only one of them was true where temp is greater than or equal to zero we
temp is greater than or equal to zero we don't execute this code the and logical
don't execute this code the and logical operator is used to check more than one
operator is used to check more than one condition we can add as many as we would
condition we can add as many as we would like to this time let's create a
like to this time let's create a variable of is sunny this will be a
variable of is sunny this will be a Boolean Boolean is sunny is it sunny
Boolean Boolean is sunny is it sunny outside I will set that to be
outside I will set that to be true not only are we going to check to
true not only are we going to check to see if our temperature is within a
see if our temperature is within a certain range we're also going to check
certain range we're also going to check and is sunny is this true so now we are
and is sunny is this true so now we are linking three different conditions all
linking three different conditions all three must be true so if all three are
three must be true so if all three are true we'll outut the following it is
true we'll outut the following it is sunny
outside let's set is sunny to be false and then we are going to set our
and then we are going to set our temperature to not
temperature to not 240
20 these two conditions are true but this one is false so we don't do any of
this one is false so we don't do any of it we skip over it with the and logical
it we skip over it with the and logical operator all conditions must be
operator all conditions must be true if is sunny we're true
true if is sunny we're true then well then we execute this code the
then well then we execute this code the temperature Falls within this range this
temperature Falls within this range this is true and this this is true and this
is true and this this is true and this is true all three conditions are true so
is true all three conditions are true so we execute this code the weather is good
we execute this code the weather is good and it is sunny
and it is sunny outside we check more than one condition
outside we check more than one condition and both must be true there's also the
and both must be true there's also the not logical operator it's a little
not logical operator it's a little different how it works is that it gives
different how it works is that it gives you the opposite you can check to see if
you the opposite you can check to see if something is not true let's add an elive
something is not true let's add an elive statement we're going to copy these
statement we're going to copy these three conditions but make one change
three conditions but make one change we're going to precede is Sunny with the
we're going to precede is Sunny with the not logical operator represented by an
not logical operator represented by an exclamation
exclamation point it checks the opposite we are
point it checks the opposite we are checking to see if something is not true
checking to see if something is not true is our temperature less than or equal to
is our temperature less than or equal to 30 and greater than or equal to zero and
30 and greater than or equal to zero and is it not
is it not Sunny so if something is normally false
Sunny so if something is normally false using the not logical operator it
using the not logical operator it becomes true if it's normally true it
becomes true if it's normally true it becomes false it gives you the opposite
becomes false it gives you the opposite for a Boolean value
for a Boolean value basically if the weather is good but
basically if the weather is good but it's not Sunny that must mean it's
it's not Sunny that must mean it's cloudy it is cloudy outside then I'll
cloudy it is cloudy outside then I'll add an emoji of a
cloud the temperature is good but we'll set is sunny to be
false the weather is good but it is cloudy
good but it is cloudy outside the temperature Falls within
outside the temperature Falls within this
this range and it is not
range and it is not Sunny the not logical operator checks to
Sunny the not logical operator checks to see if something is not true then we
see if something is not true then we have the or logical operator represented
have the or logical operator represented by two vertical bars or is similar to
by two vertical bars or is similar to the and logical operator however only
the and logical operator however only one condition needs to be true that are
one condition needs to be true that are linked by the or logical operator with
linked by the or logical operator with and both must be true let's say our
and both must be true let's say our temperature is really cold it is -10°
temperature is really cold it is -10° C but it is sunny
outside we actually don't end up doing anything we skip over the if statement
anything we skip over the if statement and the else if statement let's add
and the else if statement let's add another LF
another LF statement we're going to check to see if
statement we're going to check to see if our temperature is really hot or really
our temperature is really hot or really cold we will check if our temp is
cold we will check if our temp is greater than 30
greater than 30 or using two vertical bars temp is less
or using two vertical bars temp is less than
than zero then we'll
bad if our temperature is -10 the weather is bad with the or
-10 the weather is bad with the or logical operator at least one condition
logical operator at least one condition must be true this condition was false
must be true this condition was false but this one was true so we execute this
but this one was true so we execute this code because using the or logical
code because using the or logical operator at least one condition needs to
operator at least one condition needs to be
be true or if the temperature was 35 35°
true or if the temperature was 35 35° C this time this condition was true but
C this time this condition was true but this one was false so we execute this
this one was false so we execute this code all right let's go over another
code all right let's go over another example we're going to use these logical
example we're going to use these logical operators to validate a username when
operators to validate a username when somebody tries to set a
somebody tries to set a username so in this project we'll need a
username so in this project we'll need a scanner scanner scanner equals new
scanner scanner scanner equals new scanner we're going to type
scanner we're going to type system.in then import this
system.in then import this class then be sure to close your scanner
class then be sure to close your scanner at the end of the file scanner.
close our username has a few rules I'll add these as comments
rules I'll add these as comments username must be between 4 through 12
characters username must not
not contain
contain spaces or
underscores we'll create a string variable of
variable of username we'll create a prompt to have a
username we'll create a prompt to have a user enter in a
username enter your new username I'll use print instead of print
username I'll use print instead of print line we will assign our username using
line we will assign our username using the scanner username equals scanner.
the scanner username equals scanner. next
line we'll write a condition to check if our username is between 4 to 12
our username is between 4 to 12 characters we're going to check if our
characters we're going to check if our username is under four characters or
username is under four characters or greater than 12 characters we'll check
greater than 12 characters we'll check that within an if
that within an if statement if our username
statement if our username use the length method to return the
use the length method to return the length of this string if the length of
length of this string if the length of our username is less than four use the
our username is less than four use the or logical operator or our
or logical operator or our username the length of it using the
username the length of it using the length method is greater than 12 that
length method is greater than 12 that means our username is too short or too
means our username is too short or too long we'll output the following username
long we'll output the following username must be between 4 through 12 characters
must be between 4 through 12 characters let's perform a test
let's perform a test run enter your new username I'll type in
run enter your new username I'll type in something that's less than four
something that's less than four characters username must be between 4 to
characters username must be between 4 to 12
12 characters let's type in a really long
characters let's type in a really long username I'll just make up something
username I'll just make up something username must be between 4 to 12
username must be between 4 to 12 characters let's type in something
characters let's type in something actually within that
range oh and then we need to add an lse state statement because I
state statement because I forgot else we will
forgot else we will print
print welcome plus
username welcome whatever your username is the second part of this assignment is
is the second part of this assignment is that we need to check to make sure that
that we need to check to make sure that there are no spaces or underscores
there are no spaces or underscores within our username after the if
within our username after the if statement We'll add an L if statement to
statement We'll add an L if statement to check
check that using the contains method of
that using the contains method of strings we can check if a string
strings we can check if a string contains a certain character with our
contains a certain character with our username we will use the contains method
username we will use the contains method does our username contain any
does our username contain any spaces or does our
spaces or does our username
username contains any
contains any underscores if so we'll output the
underscores if so we'll output the following user usame must
following user usame must not contain spaces or
underscores let's perform another test run type in your first and last name
run type in your first and last name including a space username must not
including a space username must not contain spaces or
contain spaces or underscores this time I will use an
underscores this time I will use an underscore to separate the first and
underscore to separate the first and last
last name username must not contain spaces or
name username must not contain spaces or underscores let's type in a usern name
underscores let's type in a usern name that follows the
that follows the rules that seems to
rules that seems to work so that is the or logical operator
work so that is the or logical operator if at least one condition is true then
if at least one condition is true then the entire statement is true and we
the entire statement is true and we execute it all right everybody so those
execute it all right everybody so those are logical operators and checks more
are logical operators and checks more than one condition both must be true or
than one condition both must be true or checks more than one condition at least
checks more than one condition at least one needs to be true not not is a little
one needs to be true not not is a little different it checks if something is not
different it checks if something is not true basically does the inverse and well
true basically does the inverse and well everybody those are logical operators in
Java what is going on everybody in this video I need to explain while Loops in
video I need to explain while Loops in Java if I could summarize a while loop
Java if I could summarize a while loop in one sentence a while loop will repeat
in one sentence a while loop will repeat some code Forever while some condition
some code Forever while some condition remains true first I'll give you a
remains true first I'll give you a demonstration using an if statement then
demonstration using an if statement then we'll convert it to be a while loop and
we'll convert it to be a while loop and we'll see how it's useful we'll need to
we'll see how it's useful we'll need to accept user input in this demonstration
accept user input in this demonstration I will create a scanner I'm pretty sure
I will create a scanner I'm pretty sure we know how to create one by
we know how to create one by now be assured to import the scanner
now be assured to import the scanner class import java.util.scanner then be
class import java.util.scanner then be sure to close your scanner because I
sure to close your scanner because I always forget to do
always forget to do that all right we are going to create a
that all right we are going to create a string of
string of name I'll use an if statement to check
name I'll use an if statement to check to see if my name is
to see if my name is empty if name use the is empty method
empty if name use the is empty method now Java wants us to assign this name
now Java wants us to assign this name right away okay so I'm going to go ahead
right away okay so I'm going to go ahead and initialize it we can initialize it
and initialize it we can initialize it with an empty space if our name is empty
with an empty space if our name is empty which it will be we will prompt the user
which it will be we will prompt the user to enter your name I'll use print
to enter your name I'll use print instead of print line to keep it on the
instead of print line to keep it on the same line then we will assign our
same line then we will assign our variable of name name equals scanner.
variable of name name equals scanner. next
next line after we escape the if statement
line after we escape the if statement we'll output our name let's say hello
we'll output our name let's say hello Plus
Plus name so this program will work but
name so this program will work but there's one issue what if I don't type
there's one issue what if I don't type in anything when I enter my name I'll
in anything when I enter my name I'll just hit
just hit enter well we still continue with the
enter well we still continue with the rest of the program the output is hello
rest of the program the output is hello we don't display a name because we
we don't display a name because we didn't type in anything how can we
didn't type in anything how can we prevent people from doing stuff like
prevent people from doing stuff like this skipping
this skipping prompts well we could use a while loop
prompts well we could use a while loop rather than an if statement replace if
rather than an if statement replace if with while
with while what we're doing is while this condition
what we're doing is while this condition remains true continue this code Forever
remains true continue this code Forever Until this condition is no longer true
Until this condition is no longer true let's try that
let's try that again enter your name I'm just going to
again enter your name I'm just going to hit enter enter your name no enter your
hit enter enter your name no enter your name no enter your name no okay I give
name no enter your name no okay I give up I'll type in my name then we escape
up I'll type in my name then we escape the while loop hello your
the while loop hello your name so that's why a while loop Loop is
name so that's why a while loop Loop is useful we can repeat some code possibly
useful we can repeat some code possibly Forever at times we may not want a user
Forever at times we may not want a user to continue without doing something a
to continue without doing something a while loop would be really helpful for
while loop would be really helpful for that they would be stuck until this
that they would be stuck until this condition is no longer true at the end
condition is no longer true at the end of your while loop we go back to the
of your while loop we go back to the beginning to check the condition if the
beginning to check the condition if the condition is no longer true then we
condition is no longer true then we escape the while loop and move on with
escape the while loop and move on with the rest of the program there's one
the rest of the program there's one thing you should be cautious of though
thing you should be cautious of though and that is an infinite Loop let me give
and that is an infinite Loop let me give you a
you a demonstration with our while loop if we
demonstration with our while loop if we have a condition that we can't change
have a condition that we can't change from within the loop that's called an
from within the loop that's called an infinite Loop so let's say while the
infinite Loop so let's say while the number one is equal to 1 even my IDE
number one is equal to 1 even my IDE intellig is giving me a warning that 1
intellig is giving me a warning that 1 is equal to 1 is not updated inside the
is equal to 1 is not updated inside the loop I would not recommend following me
loop I would not recommend following me along for this part your computer might
along for this part your computer might freeze up but I'm going to print
freeze up but I'm going to print help I'm stuck in a loop
help I'm stuck in a loop within this while loop I have no way to
within this while loop I have no way to change it from inside of it so we're
change it from inside of it so we're going to be stuck in this while loop
going to be stuck in this while loop forever here's a
demonstration we're just going to print this code
this code forever let's check back later one
forever let's check back later one eternity later it's still going we're
eternity later it's still going we're stuck in a loop this may happen to you
stuck in a loop this may happen to you if you have some condition that you
if you have some condition that you can't change within your while loop
can't change within your while loop you'll need some way to update your
you'll need some way to update your condition
let me give you another example again we'll need our
scanner we're going to pretend that we're playing a game for a user to quit
we're playing a game for a user to quit they have to press the q key we will
they have to press the q key we will declare a string of
declare a string of response we'll use a while
response we'll use a while loop now for my condition for us to be
loop now for my condition for us to be able to escape the while
able to escape the while loop our response I'm going to use the
loop our response I'm going to use the not logical
not logical operator
operator equals a capital Q and this will be a
equals a capital Q and this will be a string so while our response does not
string so while our response does not equal Q we continue the loop forever in
equal Q we continue the loop forever in order for somebody to escape this game
order for somebody to escape this game they have to press Q to quit Java wants
they have to press Q to quit Java wants me to assign this variable right away
me to assign this variable right away and initialize it so I'll do so we don't
and initialize it so I'll do so we don't want our variable to be empty when we
want our variable to be empty when we use it to check a condition
use it to check a condition then intellig is giving us another
then intellig is giving us another warning that our response is not updated
warning that our response is not updated inside the loop if we don't update it
inside the loop if we don't update it we'll be stuck in an infinite
we'll be stuck in an infinite Loop let's pretend that we're playing a
Loop let's pretend that we're playing a game you are playing a
game then we'll output
output press Q to quit
then we will need to update our response response equals use our scanner for
response equals use our scanner for Single Character we can use
Single Character we can use next in case somebody types in a
next in case somebody types in a lowercase que we'll follow this method
lowercase que we'll follow this method with the two uppercase
with the two uppercase method if a user was to type in a
method if a user was to type in a lowercase Q we'll convert it to be an
lowercase Q we'll convert it to be an uppercase q so that it
uppercase q so that it matches once we escape the while loop
matches once we escape the while loop we'll
we'll print you have have quit the
game okay let's perform a test run you are playing a game press Q to
run you are playing a game press Q to quit no
quit no yes
yes okay as long as our response does not
okay as long as our response does not equal Q we are still playing our
equal Q we are still playing our imaginary
game in order for us to quit to escape the while loop we have to press Q to
the while loop we have to press Q to quit I will press q and we escape the
quit I will press q and we escape the loop you have quit the
loop you have quit the game while our response using the not
game while our response using the not logical operator while our response does
logical operator while our response does not equal Q continue the loop forever
not equal Q continue the loop forever let's go over another example we'll ask
let's go over another example we'll ask a user for their
a user for their age int age I will set this to be zero
age int age I will set this to be zero right
right away we'll prompt a user to enter in
away we'll prompt a user to enter in their age enter your
their age enter your age we will assign our age
age we will assign our age variable AG equal scanner. next
variable AG equal scanner. next int then at the end of this program I
int then at the end of this program I will
will print you are our variable
print you are our variable age plus years
old let's say I would like to prevent somebody from typing in a negative
somebody from typing in a negative number like -1 you are ne1 years old
number like -1 you are ne1 years old well we could use a while loop to
well we could use a while loop to reprompt the user before displaying the
reprompt the user before displaying the result so after we assign our age once
result so after we assign our age once let's use a while
let's use a while loop while age is less than zero we'll
loop while age is less than zero we'll output the
following your age can't be negative then we'll reprompt the user again we
then we'll reprompt the user again we can just copy these two lines and then
can just copy these two lines and then paste them within the while loop we'll
paste them within the while loop we'll ask the user to enter in their age again
ask the user to enter in their age again and reassign
and reassign it if we keep on typing negative
it if we keep on typing negative numbers we can't escape the while
numbers we can't escape the while loop we're stuck until we type in
loop we're stuck until we type in something that's
valid you are 21 years old that's a valid
valid number from the beginning if I type in
number from the beginning if I type in something that's valid we don't enter
something that's valid we don't enter the while loop at all it is possible to
the while loop at all it is possible to skip over
skip over it we check the condition of a while
it we check the condition of a while loop before entering it if we type in a
loop before entering it if we type in a number that's valid let's say ages
number that's valid let's say ages 25 we check the condition it's false
25 we check the condition it's false from the beginning so we don't enter the
from the beginning so we don't enter the while loop at all we skip over it and go
while loop at all we skip over it and go straight to the end in this program we
straight to the end in this program we only get caught in the while loop if we
only get caught in the while loop if we type in user input that's not
type in user input that's not valid there's a variation of the while
valid there's a variation of the while loop known as a do while loop we do some
loop known as a do while loop we do some code first and then check the
code first and then check the condition if I was to convert this code
condition if I was to convert this code to be a do while loop I would cut the
to be a do while loop I would cut the while part do this code then check the
while part do this code then check the condition at the
condition at the end this is how the program would run
end this is how the program would run now it's going to be a little bit
different your age can't be negative enter your age I am years old your age
enter your age I am years old your age can't be negative enter your age you are
can't be negative enter your age you are whatever your age is years old so with
whatever your age is years old so with the do while loop we do this code first
the do while loop we do this code first and then check the condition at the end
and then check the condition at the end where it's different compared to a
where it's different compared to a standard while loop is that with the
standard while loop is that with the standard while
standard while loop you may not enter the while loop at
loop you may not enter the while loop at all if this condition is false but with
all if this condition is false but with the do while loop you always do this
the do while loop you always do this code at least once and then check the
code at least once and then check the condition at the end let's go over one
condition at the end let's go over one last example with the do while loop
last example with the do while loop we'll prompt a user to type in a number
we'll prompt a user to type in a number that's between a certain range we will
that's between a certain range we will have int number and I will assign this
have int number and I will assign this to be zero right
to be zero right away let's use a basic while loop
away let's use a basic while loop first
first while our number is less than one we'll
while our number is less than one we'll use the or logical operator to check or
use the or logical operator to check or if our number is greater than 10
if our number is greater than 10 then do
this prompt the user to enter a number between 1 through
10 then we will assign our variable of number equals use our scanner use the
number equals use our scanner use the next int
next int method and then at the end we will print
method and then at the end we will print our
our number you picked
plus number so let's run this our number is
number so let's run this our number is set to
zero enter a number between 1 and 10 let's do negative
let's do negative 1 11 -2 one
1 11 -2 one kajillion I think I broke it okay I'll
kajillion I think I broke it okay I'll type in something that's valid like five
type in something that's valid like five you picked
you picked five rather than check the the condition
five rather than check the the condition from the beginning we could check it at
from the beginning we could check it at the end so let's convert the while loop
the end so let's convert the while loop to a do while loop do this code once and
to a do while loop do this code once and then check the
similarly so do this code once check the condition at the
condition at the end all right everybody so those are
end all right everybody so those are while Loops they allow you to execute
while Loops they allow you to execute some code possibly forever while some
some code possibly forever while some condition remains true they're really
condition remains true they're really useful when accepting user input because
useful when accepting user input because the user might not type in something
the user might not type in something that's valid and you have to keep on
that's valid and you have to keep on repr prompting them that's one good use
repr prompting them that's one good use there's two variations of while Loops a
there's two variations of while Loops a standard while loop and a do while
standard while loop and a do while loop it depends if you want to check the
loop it depends if you want to check the condition before entering the loop and
condition before entering the loop and well everybody those are while Loops in
well everybody those are while Loops in Java
hello everybody in today's video we're going to create a number guessing game
going to create a number guessing game using Java let's get started in this
using Java let's get started in this program we'll be using random numbers
program we'll be using random numbers we'll need to create a random object
we'll need to create a random object random random equals new
random random equals new random then import this class so at the
random then import this class so at the top of our Java file import
top of our Java file import java.util random this random object can
java.util random this random object can Generate random numbers for us we'll
Generate random numbers for us we'll also accept user input we'll need a
also accept user input we'll need a scanner scanner scanner equals new
scanner scanner scanner equals new scanner then within the set of
scanner then within the set of parentheses type
parentheses type system.in then import this class as well
system.in then import this class as well import
import java.util.scanner we have a random
java.util.scanner we have a random object to Generate random numbers and a
object to Generate random numbers and a scanner object to accept user
scanner object to accept user input what are the different variables
input what are the different variables we'll need we'll need the following an
we'll need we'll need the following an integer to hold our
integer to hold our guess so let's say we're going to guess
guess so let's say we're going to guess a random number between 1 and 100 we'll
a random number between 1 and 100 we'll use the scanner to accept an integer and
use the scanner to accept an integer and place it within this variable of
place it within this variable of guess for example the guess might be
guess for example the guess might be 50 we need to keep track of the amount
50 we need to keep track of the amount of attempts it took a user to get the
of attempts it took a user to get the correct number int attempts we'll assign
correct number int attempts we'll assign these
these later and we'll need a random number int
later and we'll need a random number int random number
random number let's go ahead and assign this right
let's go ahead and assign this right away to generate a random number we're
away to generate a random number we're going to use our random
going to use our random object use the next int method of a
object use the next int method of a random object within this method we can
random object within this method we can list two numbers a range if I would like
list two numbers a range if I would like a number between let's say 1 and 10 my
a number between let's say 1 and 10 my two numbers would be 1 comma 11 the
two numbers would be 1 comma 11 the first number is inclusive the second
first number is inclusive the second number is
number is exclusive let's perform a test run of a
exclusive let's perform a test run of a random number I just want to be sure
random number I just want to be sure that it's generating correctly when
that it's generating correctly when writing a program it is a good idea to
writing a program it is a good idea to test your code every once in a while
test your code every once in a while just to be sure that everything is
just to be sure that everything is working so we should get random numbers
working so we should get random numbers between 1 and 10 1 10 5 8 good enough a
between 1 and 10 1 10 5 8 good enough a random number stores a random number
random number stores a random number after generating
after generating it let's create a welcome message let's
it let's create a welcome message let's say number guessing
say number guessing game we will prompt the
game we will prompt the user guess a
user guess a number
number between let's start with 1 through 10
between let's start with 1 through 10 later on we'll increase it to
100 now we'll need a while loop but not just any while loop we'll create a do
just any while loop we'll create a do while loop so do this code once while
while loop so do this code once while this condition remains true and let me
this condition remains true and let me zoom in a little
zoom in a little bit so what's our condition going to be
bit so what's our condition going to be we're going to continue playing this
we're going to continue playing this game while our
game while our guess does not equal our random number
guess does not equal our random number we'll keep on playing until we get the
we'll keep on playing until we get the random number exclamation point equals
random number exclamation point equals means not equal so if our guess does not
means not equal so if our guess does not equal our random number this return
equal our random number this return turns true then we want to keep playing
turns true then we want to keep playing while our guess doesn't equal the random
while our guess doesn't equal the random number within this do while
number within this do while loop will prompt the user to enter in
loop will prompt the user to enter in their guess I'm going to use print line
their guess I'm going to use print line instead of print for guess a number
instead of print for guess a number between 1 and
between 1 and 10 now we'll prompt the user to enter a
10 now we'll prompt the user to enter a number enter a guess enter a
number enter a guess enter a guess for this I'll use print instead of
guess for this I'll use print instead of print line we will assign Our Guest
print line we will assign Our Guest variable equal to use our scanner use
variable equal to use our scanner use the next int
method we're also keeping track the amount of attempts it takes a user to
amount of attempts it takes a user to get the correct
get the correct number so we can increment attempts by
number so we can increment attempts by adding
Plus+ and let's go ahead and initialize attempts we'll set that to be zero
temporarily outside the while loop I'm going to
going to print you have
print you have one my random number right now is only
one my random number right now is only between 1 and 10 I'm just going to keep
between 1 and 10 I'm just going to keep guessing until we get the right
number so I'll just start with one and go all the way to
10 the answer was nine we escaped the wild
wild Loop so we know that this is working
Loop so we know that this is working currently one thing this program is
currently one thing this program is missing is that we'll want to give a
missing is that we'll want to give a user a clue if their guess is too low or
user a clue if their guess is too low or too high because we have no way to
too high because we have no way to tell I'm just typing in random numbers
tell I'm just typing in random numbers and I have no clue how close I am to the
and I have no clue how close I am to the actual number that we need to
actual number that we need to guess let's get rid of this print
guess let's get rid of this print statement we were using it for testing
statement we were using it for testing purposes within the do while loop we'll
purposes within the do while loop we'll write an if statement we'll check if our
write an if statement we'll check if our guess is less than our random
guess is less than our random number that means we guess too
number that means we guess too low if that's the case we'll output the
low if that's the case we'll output the following two low try
again else if our guess is greater than our random
if our guess is greater than our random number that means we guess too
number that means we guess too high too high try
high too high try again if our guess isn't lower than our
again if our guess isn't lower than our random number and our guess isn't
random number and our guess isn't greater than our random number that
greater than our random number that means our guess must equal the random
means our guess must equal the random number so if that's the case we would be
number so if that's the case we would be executing this lse statement because the
executing this lse statement because the preceding two conditions would be false
preceding two conditions would be false that means we have the right answer the
that means we have the right answer the right guess so we'll output the
correct the let me zoom out the number
out the number was plus our random
number and then we'll display the amount of attempts it
of attempts it took number of attempts
took number of attempts plus our variable of attempts after each
plus our variable of attempts after each guess we increment it by
guess we increment it by one the last thing I'm forgetting is to
one the last thing I'm forgetting is to close my scanner because I always forget
close my scanner because I always forget to close
to close it scanner.
it scanner. close okay let's perform a test run
close okay let's perform a test run we're only guessing a number between 1
we're only guessing a number between 1 and 10
and 10 currently I'll guess something right in
currently I'll guess something right in the middle five too low try again the
the middle five too low try again the random number we have to guess should be
random number we have to guess should be between 5 and 10 then I'll go with seven
between 5 and 10 then I'll go with seven too low 8 too low nine too low okay it
too low 8 too low nine too low okay it must be 10 then correct the number was
must be 10 then correct the number was 10 number of attempts it took
10 number of attempts it took five we're going to improve this code
five we're going to improve this code now what if we would like the numbers 1
now what if we would like the numbers 1 through 100 this time well we could make
through 100 this time well we could make this program a little more flexible
this program a little more flexible instead of hardcoding these numbers
instead of hardcoding these numbers within the next integer method we'll
within the next integer method we'll Place some variables here instead we
Place some variables here instead we will create int Min equals whatever you
will create int Min equals whatever you want the minimum to be let's say one int
want the minimum to be let's say one int Max I will set the max to be 100 let's
Max I will set the max to be 100 let's replace these two
replace these two numbers the first one will be Min comma
numbers the first one will be Min comma Max so these variables behave as if they
Max so these variables behave as if they were these numbers within this range the
were these numbers within this range the second number is exclusive so TW include
second number is exclusive so TW include 100 I'm going to add +
100 I'm going to add + one give me the numbers between 1 and
one give me the numbers between 1 and 100 within this print statement let's
100 within this print statement let's use print F
use print F instead we'll replace these numbers with
instead we'll replace these numbers with the format specifier a placeholder we
the format specifier a placeholder we will display an integer so we need D
will display an integer so we need D let's do the same thing with 10
d uh let's do comma Min comma Max and then add a new line at the
end let's do one final run so now we're guessing a number
run so now we're guessing a number between one and 100 I'll guess something
between one and 100 I'll guess something right in the middle too high try again
right in the middle too high try again our numberers going to be between 1 and
our numberers going to be between 1 and 50 then 25 too high 12 too high 6 too
50 then 25 too high 12 too high 6 too high three
high three too low between three and six four
too low between three and six four correct the number was four the number
correct the number was four the number of attempts it took six
of attempts it took six attempts all right everybody so that is
attempts all right everybody so that is a number guessing game that you can
a number guessing game that you can create using
Java hi there everybody so in this video I'm going to explain four Loops in Java
I'm going to explain four Loops in Java a four Loop is similar to a while loop
a four Loop is similar to a while loop however a for Loop executes some code a
however a for Loop executes some code a certain amount of times a for Loop is
certain amount of times a for Loop is different from a while loop a while loop
different from a while loop a while loop could execute an infinite amount of
could execute an infinite amount of times until its condition is no longer
times until its condition is no longer true so with for Loops we want to do
true so with for Loops we want to do something a certain amount of times to
something a certain amount of times to create a for Loop type four parentheses
create a for Loop type four parentheses curly braces now within the condition of
curly braces now within the condition of the for Loop there's three statements
the for Loop there's three statements each is separated with a
each is separated with a semicolon we have statement one
semicolon we have statement one statement two and statement three the
statement two and statement three the first statement is used for ini ization
first statement is used for ini ization we can create a counter to keep track of
we can create a counter to keep track of how many times we have iterated this
how many times we have iterated this Loop basically we're declaring a
Loop basically we're declaring a variable a counter this will be int now
variable a counter this will be int now a common practice for a for Loop is to
a common practice for a for Loop is to create a counter named I meaning index
create a counter named I meaning index in I equal Z or some other number I is
in I equal Z or some other number I is going to be used as a counter within
going to be used as a counter within this Loop also known as a loop control
this Loop also known as a loop control variable the second statement is a
variable the second statement is a condition when do we want to
condition when do we want to stop maybe we would like to execute some
stop maybe we would like to execute some code 10 times we'll continue this loop
code 10 times we'll continue this loop as long as I is less than
as long as I is less than 10 now the third statement the third
10 now the third statement the third statement is the step we can increment
statement is the step we can increment our counter of I by One or another
our counter of I by One or another number or even decrement after each
number or even decrement after each iteration let's increase I by One
iteration let's increase I by One i++ let's perform a test run I'm just
i++ let's perform a test run I'm just going to print the word
pizza so we should execute this code 10 times using this for Loop 1 2 3 4 5 6 7
times using this for Loop 1 2 3 4 5 6 7 8 9
8 9 10 so a for Loop is good if you want to
10 so a for Loop is good if you want to repeat some code a certain amount of
repeat some code a certain amount of times but there's a little bit of setup
times but there's a little bit of setup you have to do we'll need some sort of
you have to do we'll need some sort of index or counter a condition in which
index or counter a condition in which you want to stop and you'll need to
you want to stop and you'll need to update the counter
update the counter one way or another
one way or another initialization condition update we can
initialization condition update we can also print this index of I rather than
also print this index of I rather than printing the word Pizza let's print I to
printing the word Pizza let's print I to see what we're working with during the
see what we're working with during the first iteration I is zero after our Loop
first iteration I is zero after our Loop is complete we increment I by One our
is complete we increment I by One our counter so we have 0 1 2 3 4 5 6 7 8 9
counter so we have 0 1 2 3 4 5 6 7 8 9 We're looping 10 times
We're looping 10 times but we set I to be zero to begin with if
but we set I to be zero to begin with if I were to set I to be 1 and I want to
I were to set I to be 1 and I want to iterate 10 times I could say while I is
iterate 10 times I could say while I is less than or equal to
less than or equal to 10 so now we're starting at 1 and
10 so now we're starting at 1 and counting up to
counting up to 10 we can even decrement
10 we can even decrement to let's set I to be 10 we'll continue
to let's set I to be 10 we'll continue the loop as long as I is greater than
the loop as long as I is greater than zero to decrement we'll set I to be
zero to decrement we'll set I to be minus
minus minus now we're starting at 10 and
decrementing but we're still looping 10 times let's go back to the
beginning using the update statement we can even increment by a certain number
can even increment by a certain number instead of incrementing by one let's
instead of incrementing by one let's increment by two and see what
increment by two and see what happens so this time we start at one and
happens so this time we start at one and update our counter of I two each time or
update our counter of I two each time or even three i+ equal
even three i+ equal 3 1 4 7
3 1 4 7 10 we can decrement by a given
10 we can decrement by a given number let's set I to be 10 we'll
number let's set I to be 10 we'll continue this loop as long as I is
continue this loop as long as I is greater than zero and we will decrement
greater than zero and we will decrement our step we will decrement by 2 i - = 2
our step we will decrement by 2 i - = 2 now we're starting at 10 and
now we're starting at 10 and decrementing by two or even three IUS =
decrementing by two or even three IUS = 3
10741 for this next example we're going to accept user input again we'll need a
scanner import the scanner class and close your scanner at the end
we'll create a prompt enter how many times you want to
Loop I'll create a variable of Max Max will equal use our scanner use the next
will equal use our scanner use the next int
int method and now we're going to create a
method and now we're going to create a loop a for Loop
statements each separated with a semicolon we'll need an index or counter
semicolon we'll need an index or counter to keep track of how many times we have
to keep track of how many times we have looped let's say in I equals
looped let's say in I equals 0 for the next statement what's our
0 for the next statement what's our condition we want to continue as long as
condition we want to continue as long as I is less than the max I is less than
I is less than the max I is less than our Max variable
our Max variable then increment I by
else let's try this how many times do you want to Loop let's Loop five
you want to Loop let's Loop five times 1 2 3 4
times 1 2 3 4 5 again we set I to be zero so that's
5 again we set I to be zero so that's why we're beginning with
why we're beginning with zero if you would rather begin with one
zero if you would rather begin with one we can set I to be 1 then the condition
we can set I to be 1 then the condition would be I is less than or equal to Max
would be I is less than or equal to Max let's try that again let's Loop six
let's try that again let's Loop six times 1 2 3 4 5
times 1 2 3 4 5 6 all right now we're going to create a
6 all right now we're going to create a mini
mini project we'll create a program to
project we'll create a program to simulate a
countdown perhaps we have a variable of int
int start let's start at 10 we're counting
start let's start at 10 we're counting down from
down from 10 then we'll create a for
10 then we'll create a for Loop we will set our index of I equal to
Loop we will set our index of I equal to our
our start our start variable behaves as if
start our start variable behaves as if it was the number
it was the number 10 we'll continue as long as I is
10 we'll continue as long as I is greater than zero then we will decrement
greater than zero then we will decrement by one with IUS
by one with IUS minus during each iteration let's just
minus during each iteration let's just print
print I then when we escape the the for Loop
I then when we escape the the for Loop let's print happy New
let's print happy New Year kind of like it's a countdown to a
Year kind of like it's a countdown to a new year here's what we have
currently we start at 10 count down to one then display happy New Year if you
one then display happy New Year if you would like we can use the thread class
would like we can use the thread class and have our program sleep for about 1
and have our program sleep for about 1 second between each
second between each Loop here's how you can do that after
Loop here's how you can do that after printing I this is a little Advan Java
printing I this is a little Advan Java at this level you don't need to
at this level you don't need to understand how this works but we're
understand how this works but we're going to use the thread class called The
going to use the thread class called The Sleep Method then pass in an amount of
Sleep Method then pass in an amount of milliseconds in which we would like to
milliseconds in which we would like to sleep 1,000
sleep 1,000 milliseconds now Java wants us to add
milliseconds now Java wants us to add the
the following Java wants this method of main
following Java wants this method of main to throw this exception if our thread is
to throw this exception if our thread is interrupted this is intermediate Java we
interrupted this is intermediate Java we will need the section of code in order
will need the section of code in order for our program to sleep after you
for our program to sleep after you finish this lesson be sure to remove
finish this lesson be sure to remove throws interrupted exception we'll no
throws interrupted exception we'll no longer need it print I then our program
longer need it print I then our program is going to sleep for 1 second 1,000
is going to sleep for 1 second 1,000 milliseconds all right and here's our
milliseconds all right and here's our mini
mini project 10 9 8 7 6 5 4 3 2 one Happy New
project 10 9 8 7 6 5 4 3 2 one Happy New Year
Year let's modify this program a little bit
let's modify this program a little bit now we'll use a scanner to accept user
now we'll use a scanner to accept user input scanner scanner equals new
input scanner scanner equals new scanner we have already imported the
scanner we have already imported the class with start we're going to accept
class with start we're going to accept some user
some user input but we'll need a
input but we'll need a prompt how many seconds to countown
from we will assign start to be use our scanner then use the next int method
again let's say I would like to count down from
20 and it looks like it's working I'll fast forward the video till we get to
fast forward the video till we get to the
the end 3 2
end 3 2 1 happy New
1 happy New Year so those are four Loops we can
Year so those are four Loops we can execute some code a certain amount of
execute some code a certain amount of times it's very similar to a while loop
times it's very similar to a while loop in fact there's a lot of overlap where
in fact there's a lot of overlap where you could use either a for Loop or a
you could use either a for Loop or a while loop use a for Loop if you want to
while loop use a for Loop if you want to do something a limited amount of times
do something a limited amount of times and well everybody those are four Loops
and well everybody those are four Loops in
Java I have a pretty short video for you today we're going to discuss two
today we're going to discuss two important keywords when it comes to
important keywords when it comes to Loops break and continue break is used
Loops break and continue break is used to break out of a loop continue skips
to break out of a loop continue skips the current iteration of a loop think of
the current iteration of a loop think of the break keyword as the stop button on
the break keyword as the stop button on a remote continue would be similar to
a remote continue would be similar to skip with break we're stopping with
skip with break we're stopping with continuing we're skipping let me give
continuing we're skipping let me give you a
you a demonstration let's create a for Loop
demonstration let's create a for Loop that will iterate 10 times let's say in
that will iterate 10 times let's say in I equals 0 will continue as long as I is
I equals 0 will continue as long as I is less than
less than 10 then increment I by 1 during each
10 then increment I by 1 during each iteration I'll just print I then add a
iteration I'll just print I then add a space here's what we
space here's what we got we have the numbers 0 through 9 so
got we have the numbers 0 through 9 so let's say when we reach five I would
let's say when we reach five I would like to break out of the loop we're
like to break out of the loop we're going to stop it well I could add an if
going to stop it well I could add an if statement let's
statement let's say if I is equal to 5 then we will use
say if I is equal to 5 then we will use the break keyword
the break keyword and break out of the loop
and break out of the loop entirely here's what
entirely here's what happens once we hit five we break out of
happens once we hit five we break out of the loop previously we continued all the
the loop previously we continued all the way until
way until 9 now with the continue keyword we don't
9 now with the continue keyword we don't break out of the loop we just skip the
break out of the loop we just skip the current iteration like a skip button on
current iteration like a skip button on a remote this time let's use continue
a remote this time let's use continue rather than
rather than break and we'll see the differences
break and we'll see the differences between the two
now since we're using continue the number five is missing we skipped that
number five is missing we skipped that specific cycle of the loop and went back
specific cycle of the loop and went back to the beginning that's why five is
to the beginning that's why five is missing between four and six but we
missing between four and six but we still continue to the end when working
still continue to the end when working with loops if you ever need to break out
with loops if you ever need to break out you can use the break keyword to skip
you can use the break keyword to skip the occurrent iteration you can use
the occurrent iteration you can use continue and well everybody that is both
continue and well everybody that is both the break and continue keywords in Java
the break and continue keywords in Java hello again friends today I'm going to
hello again friends today I'm going to explain nested Loops in Java a nested
explain nested Loops in Java a nested Loop is really just a loop inside of
Loop is really just a loop inside of another loop you often see nested Loops
another loop you often see nested Loops within a matrix or matrices or when we
within a matrix or matrices or when we reach the topic of data structures and
reach the topic of data structures and algorithms they might not come up for a
algorithms they might not come up for a while yeah this can be any combination
while yeah this can be any combination of for Loops or while Loops any kind of
of for Loops or while Loops any kind of loop inside of another loop let me give
loop inside of another loop let me give you a
you a demonstration let's say I would like to
demonstration let's say I would like to print the numbers 1 through N9 I can do
print the numbers 1 through N9 I can do that pretty easily with a for Loop so we
that pretty easily with a for Loop so we will create a for loop I will set an
will create a for loop I will set an index of I equal to 1 we'll continue
index of I equal to 1 we'll continue this loop as long as I is less than or
this loop as long as I is less than or equal to 9 then I will increment I by
equal to 9 then I will increment I by One during each iteration I will display
One during each iteration I will display I so this will print the
I so this will print the numbers 1- N9 or if you prefer you can
numbers 1- N9 or if you prefer you can have it all on the same l line by using
have it all on the same l line by using print instead of print line then it
print instead of print line then it would look something like
would look something like this 1 2 3 4 5 6 7 8 9 you can even
this 1 2 3 4 5 6 7 8 9 you can even separate them with the space after
separate them with the space after printing our index of I let's print a
printing our index of I let's print a space
space character and now the output looks
character and now the output looks something like
something like this what if you would like to do this
this what if you would like to do this code three times let's say print the
code three times let's say print the numbers 1 through 9 three
numbers 1 through 9 three times well you could copy and paste this
times well you could copy and paste this for
for Loop then do that two additional
Loop then do that two additional times so we have the numbers 1 through 9
times so we have the numbers 1 through 9 three
three times to put each row on a new line can
times to put each row on a new line can use an empty print line
statement then it would look something like this a
like this a matrix we seem to be repeating our code
matrix we seem to be repeating our code a lot in programming we like to follow
a lot in programming we like to follow the dry principle don't repeat yourself
the dry principle don't repeat yourself if you don't have to
if you don't have to instead why don't we create a for Loop
instead why don't we create a for Loop and stick this for Loop inside of that
and stick this for Loop inside of that Loop let's create a for Loop to iterate
Loop let's create a for Loop to iterate three times I will create an index of I
three times I will create an index of I equal to 1 we'll continue as long as I
equal to 1 we'll continue as long as I is less than or equal to three then
is less than or equal to three then increment I by One all we're going to do
increment I by One all we're going to do is take our code including the for Loop
is take our code including the for Loop and stick it within this other for Loop
and stick it within this other for Loop do pay attention to the
do pay attention to the indentation but we have we have one
indentation but we have we have one problem we're reusing this index of I
problem we're reusing this index of I you can see that Java is already giving
you can see that Java is already giving us a warning here's what
us a warning here's what happens variable I is already defined in
happens variable I is already defined in method
method main if we have a loop inside of another
main if we have a loop inside of another loop we can't use the same
loop we can't use the same index a common naming convention for a
index a common naming convention for a nested Loop is to use an index of J
nested Loop is to use an index of J rather than
rather than I because J comes next in the alphabet
I because J comes next in the alphabet after I
after I instead of printing I we're going to
instead of printing I we're going to print
print J let's see how this works and here's
J let's see how this works and here's our Matrix of data we're printing our
our Matrix of data we're printing our index of J three
times after escaping the nested for Loop we have a print line statement here if I
we have a print line statement here if I were to get rid of
were to get rid of that we'll print the numbers 1 through 9
that we'll print the numbers 1 through 9 three times all on the same
three times all on the same line let's put that back in
line let's put that back in nested Loops are really good when you're
nested Loops are really good when you're working with a matrix of data nested
working with a matrix of data nested Loops come up pretty often in the topic
Loops come up pretty often in the topic of data structures and algorithms
of data structures and algorithms because we have to Loop over sets of
because we have to Loop over sets of data now we're going to cover a mini
data now we're going to cover a mini project we're going to create a matrix
project we're going to create a matrix of a symbol that a user is going to type
of a symbol that a user is going to type in a user will set the rows and columns
in a user will set the rows and columns for this Matrix we'll declare the
for this Matrix we'll declare the following variables int
following variables int rows int
rows int columns and and Char
symbol we'll need a scanner so let's declare that we'll need a scanner
declare that we'll need a scanner scanner scanner equals new
scanner scanner equals new scanner within the set of parentheses
scanner within the set of parentheses type
type system.in let's be sure to import this
system.in let's be sure to import this class of scanner at the top of our Java
class of scanner at the top of our Java file and close the scanner when we're
file and close the scanner when we're done with it scanner.
close we're going to accept some user input a user is going to specify the
input a user is going to specify the rows the columns and the symbol we're
rows the columns and the symbol we're going to
going to use let's create some
use let's create some prompts enter the
prompts enter the number of rows I'll use print instead of
number of rows I'll use print instead of print line we will assign our variable
print line we will assign our variable of
of rows equal to use our scanner use the
rows equal to use our scanner use the next int
next int method then let's do this with columns
method then let's do this with columns enter the number of
columns columns equals scanner. nextend and the symbol we're going to
use enter the symbol to use we will assign our symbol equal to
use we will assign our symbol equal to scanner.
scanner. nextt and we can use the chart at method
give me the character at index of zero let's create a for Loop for the
zero let's create a for Loop for the columns
first let me zoom in we're going to set in
in we're going to set in I we can set it equal to
I we can set it equal to zero we'll continue as long as I is less
zero we'll continue as long as I is less than our columns whatever the user types
than our columns whatever the user types in then increment I by One
in then increment I by One during each
during each iteration I'll use print instead of
iteration I'll use print instead of print line we will print our
print line we will print our symbol let's perform a test
symbol let's perform a test run enter the rows it doesn't matter we
run enter the rows it doesn't matter we didn't set up the rows yet uh for the
didn't set up the rows yet uh for the columns let's do
columns let's do eight enter the symbol to use Let's
eight enter the symbol to use Let's do let's do a dollar sign that'd be
do let's do a dollar sign that'd be cool we have the column set set up
cool we have the column set set up currently we should have eight dollar
currently we should have eight dollar signs 1 2 3 4 5 6 7 8 we need to repeat
signs 1 2 3 4 5 6 7 8 we need to repeat this for Loop for as many rows as we
this for Loop for as many rows as we have so we're going to stick this Loop
have so we're going to stick this Loop within another
loop with our nested Loop let's replace our index of I with j
for the outer for Loop we will create a new index of I equal to zero we'll
new index of I equal to zero we'll continue this as long as I is less than
continue this as long as I is less than the rows the number of rows that a user
the rows the number of rows that a user types in then increment I by
types in then increment I by One let's perform another test
One let's perform another test run let's say I would like three rows of
run let's say I would like three rows of six and I will use an at
six and I will use an at sign so these are all on the same line
sign so these are all on the same line we should have a total of
we should have a total of 18 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15