Curso Java. Estructuras principales VI. Clase Math. Vídeo 9
Summary
TLDREste curso de programación en Java, dirigido a principiantes, aborda conceptos fundamentales como las estructuras de datos y las clases. Se explica cómo realizar operaciones matemáticas avanzadas utilizando la clase Math, incluyendo raíces cuadradas, potencias y redondeo. Se introducen las clases predefinidas y personalizadas en Java, y se enfatiza la importancia de la API de Java para acceder a cientos de clases y métodos. El vídeo también explora cómo utilizar el método sqrt() para calcular raíces cuadradas y resalta la precisión de Java con tipos de datos, utilizando Eclipse para demostrar la creación y ejecución de un programa simple.
Takeaways
- 😀 Este curso de programación en Java aborda la creación de programas desde cero.
- 🔢 Se ha discutido cómo declarar variables y constantes, así como los diferentes tipos de datos en Java.
- 🧮 Se exploraron los operadores aritméticos básicos como la suma, la resta, la multiplicación y la división.
- 📚 Se avanzó en el conocimiento de las estructuras principales y se introdujeron cálculos numéricos más avanzados como raíces, elevado al cuadrado y redondeo de números.
- 👨🏫 Se enfatizó la importancia de las clases en Java, tanto las propias como las predefinidas, y se explicó la diferencia entre ellas.
- 📚 Se mencionaron clases predefinidas en Java, como String, Math, Array y System, que facilitan tareas comunes en la programación.
- 🔍 Se presentó la API de Java (Java API) como una herramienta esencial para consultar clases y métodos predefinidos.
- 💻 Se utilizó Eclipse para demostrar cómo se programa en Java y se abrió un nuevo espacio de trabajo para crear una clase llamada 'Calculations'.
- 🛠️ Se explicó el uso del método sqrt() de la clase Math para calcular la raíz cuadrada de un número y se corrigió un error de tipo de datos.
- 🔄 Se mencionó que se abordará el uso del método round() y la técnica de recast en futuras lecciones.
Q & A
¿Qué temas se abordan en el curso de programación en Java mencionado en el guion?
-El curso aborda la declaración de variables, tipos de datos en Java, operadores aritméticos, y avanza hacia el uso de la clase Math para realizar cálculos numéricos avanzados como raíces cuadradas, elevar a una potencia, redondeo de números, entre otros.
¿Qué es una clase en el contexto de programación en Java?
-Una clase en Java es una estructura de datos que actúa como una plantilla para objetos, puede contener métodos y variables, y es un concepto fundamental ya que todos los programas Java deben estar compuestos por al menos una clase.
¿Cuáles son las dos tipos de clases que se pueden tener en Java según el guion?
-Las dos tipos de clases en Java son las clases propias, que son aquellas que el programador crea, y las clases predefinidas, que vienen incorporadas en el lenguaje de programación Java.
¿Qué es la clase Math en Java y qué propósito cumple?
-La clase Math es una clase predefinida en Java que contiene métodos estáticos para realizar cálculos matemáticos como raíces cuadradas, potencias, redondeo, entre otros.
¿Qué es la API de Java y cómo se relaciona con las clases predefinidas?
-La API de Java es una biblioteca que contiene todas las clases del lenguaje de programación Java, y es una herramienta que los programadores consultan frecuentemente para usar las clases y métodos predefinidos en sus programas.
¿Cómo se puede utilizar el método sqrt() de la clase Math para calcular la raíz cuadrada de un número?
-El método sqrt() se utiliza pasando un número como argumento y devuelve la raíz cuadrada de ese número. El resultado es de tipo double, por lo que se debe almacenar en una variable de tipo double.
¿Qué es un error de conversión de tipos en Java y cómo se presenta en el guion?
-Un error de conversión de tipos ocurre cuando se intenta almacenar un dato de un tipo en una variable de otro tipo incompatible. En el guion, se presenta un ejemplo donde se intenta almacenar el resultado de sqrt(), que es un double, en una variable de tipo int, lo que causa un error.
¿Qué herramienta de desarrollo se utiliza para ilustrar la creación y ejecución de código en el guion?
-El guion utiliza Eclipse, un entorno de desarrollo integrado (IDE), para crear, editar, y ejecutar programas en Java.
¿Qué métodos adicionales de la clase Math se mencionan en el guion para futuras sesiones?
-Se mencionan métodos como round() para redondear números, pow() para elevar a una potencia, y la posibilidad de explorar el concepto de recast, que es el cambio de un tipo de dato a otro.
¿Qué es un constante en Java y cómo se relaciona con la clase Math?
-Una constante en Java es una variable cuyo valor no puede cambiar después de que se le asigne. La clase Math tiene constantes predefinidas, como PI, que almacenan valores fijos importantes para cálculos matemáticos.
Outlines
📚 Introducción al curso de programación en Java
El primer párrafo presenta un curso de programación en Java, enfocándose en la explicación de las estructuras principales del lenguaje. Se menciona que se han cubierto temas como la declaración de variables y constantes, así como los tipos de datos en Java. También se recuerda que en el vídeo anterior se exploraron los operadores aritméticos básicos. El vídeo actual promueve avanzar en el conocimiento de estas estructuras, introduciendo cálculos numéricos más avanzados como raíces, elevación al cuadrado y redondeo de números. Se destaca la importancia de estas habilidades para los programadores principiantes y se anuncia la exploración de la clase Math en Java para realizar estos cálculos.
🏫 Importancia de las clases en Java y la biblioteca de clases (API)
El segundo párrafo profundiza en el concepto de clases en Java, explicando que todo programa en Java debe estar compuesto por al menos una clase y que los programas suelen estar compuestos por múltiples clases. Se diferencia entre clases propias, que son aquellas que el programador crea, y clases predefinidas que vienen incorporadas en el lenguaje. Se ilustra con ejemplos como la clase String para manejar cadenas de caracteres y la clase Math para realizar cálculos matemáticos. Además, se introduce la API de Java como una biblioteca de clases y métodos que el programador puede consultar y utilizar en sus programas.
🔢 Explorando la clase Math y sus métodos matemáticos
El tercer párrafo se centra en la clase Math y sus métodos para realizar cálculos matemáticos. Se mencionan métodos como sqrt para calcular raíces cuadradas, pow para elevar un número a una potencia y otros métodos para funciones trigonométricas como sin y tan. También se habla sobre el concepto de redondeo y la existencia de constantes predefinidas como PI y E. Se enfatiza la importancia de manejar la API de Java para aprender y utilizar estos métodos en la programación.
💻 Creación y errores en la programación con Java
El cuarto párrafo describe el proceso de creación de una clase en Java y la ejecución de un ejemplo simple para calcular la raíz cuadrada de un número. Se detalla cómo se declara una variable y se utiliza el método sqrt de la clase Math, pero se comete un error al intentar almacenar un valor decimal en una variable de tipo entero. Se explica la rigidez de Java con los tipos de datos y cómo el editor Eclipse ayuda a identificar y solucionar estos errores, proporcionando información sobre los métodos y sus tipos de datos esperados.
✅ Solución de errores y uso de la clase Math en Java
El último párrafo concluye con la corrección del error mencionado anteriormente, cambiando el tipo de la variable para almacenar el resultado decimal de la raíz cuadrada. Se muestra la ejecución del programa y el resultado esperado, que es el número 3.0. Además, se anuncia que en futuros vídeos se explorarán otros métodos de la clase Math, como el redondeo y el uso de métodos con dos parámetros, así como el concepto de recast para cambiar un tipo de datos a otro.
Mindmap
Keywords
💡Clases
💡Variables
💡Operadores aritméticos
💡Raíz cuadrada
💡Tipos de datos
💡Métodos
💡API de Java
💡Eclipse
💡Errores de conversión de tipos
💡Constantes
Highlights
Bienvenido a otro entrega de curso de programación en Java.
Se discute la importancia de las estructuras principales en Java.
Se explica cómo declarar variables y constantes en Java.
Se exploran los tipos de datos en Java.
Se enseña el uso de operadores aritméticos para realizar operaciones básicas.
Se avanza en el conocimiento de las estructuras principales y se mencionan otros cálculos numéricos.
Se mencionan cálculos como raíces, elevados al poder y redondeo de números.
Se habla sobre la necesidad de conocer el manejo de la clase Math para realizar cálculos en Java.
Se aclara la diferencia entre clases propias y clases predefinidas en Java.
Se explica que cada programa en Java debe estar compuesto por al menos una clase.
Se menciona la importancia de la clase Math para realizar cálculos matemáticos en Java.
Se presentan ejemplos de clases predefinidas en Java, como String, Math, Array y Thread.
Se habla sobre la imposibilidad de memorizar todas las clases y métodos predefinidos y la necesidad del API de Java.
Se muestra cómo se puede consultar la biblioteca de clases de Java (API) en línea.
Se discute la importancia de las clases y sus métodos en la programación en Java.
Se explica cómo se pueden utilizar métodos de la clase Math, como sqrt para calcular raíces cuadradas.
Se menciona el uso de la constante pi en la clase Math para cálculos trigonométricos.
Se ilustra cómo se puede encontrar y utilizar métodos de la clase Math con la ayuda del IDE Eclipse.
Se da un ejemplo práctico de cómo se declara una variable y se le asigna el resultado de una operación matemática utilizando la clase Math.
Se explica el error de tipo de conversión y cómo solucionarlo al utilizar métodos que devuelven un tipo de datos específico.
Se muestra cómo ejecutar un programa simple en Eclipse que utiliza la clase Math para calcular la raíz cuadrada de un número.
Se invita a los espectadores a seguir el curso para aprender más sobre el uso de la clase Math y otros conceptos en futuros videos.
Transcripts
hello that such welcome to another delivery
this java programming course from
zero we were watching in videos
previous main structures
of language we have already seen how
declare variables like declare
constant we talked about the types of
data in java and in the last video if
you remember, we were seeing how
use the arithmetic operators to
do simple operations such as
sums subtraction multiplications and
divisions in this video we follow
advancing in the knowledge of
main structures and let's see
how to perform other numerical calculations
in java
when we say other numerical calculations
we refer for example to roots
square we mean to raise a
number to a power rounding of
numbers and so on
and to do these calculations that are
essential when programming
maybe those who are starting in the
world of programming because you can not
see the need to learn to do
all this when creating a program
but I already anticipate that it is
essential and to be able to do these
calculations in java we have to know the
handling of the class more and that is it turns out
that to make these calculations we must
use in java this class the term
of class because maybe we still find
everything familiar maybe serves us a little
because we are starting to program in
java we are not in the beginning yet
that we know about the classes that we know
of the class concept as we said in
previous videos all java program
must be composed of at least one
class as usual is that a program in
java is composed of more than one class
but at least it has to be formed of
a class and we the examples that
We have been doing so far
they have been composed of a class not
we have to keep moving forward in this
class concept although not yet
we are in a position to deepen
everything you need but
we have to know at least two things
and is that besides that every program
java has to be composed at least
of a class the classes in java can
be of two types we can have in java
own classes and we have in java classes
predefined what is the difference between
one and the other
own classes are what we create
us as we have done then in
previous videos for example now
we have one of the classes on screen
what we did in the last good video
because this would be a class of its own is a
class that we have created very
simple and this class has a unique
method another term that still does not
we control completely the method that has
this class is the main all class method
in java all program in java must have
at least one main method unless it is
a play program that we already talked about
it at the time in the applets it
replace the main with the line method
but good for the moment this is not us
worry we'll see later
these are the classes that we have
gone so far very simple
Well, these are our own classes
classes developed by us
however we also have another kind of
classes that are the predefined ones and these
they are classes are already built inside
of the java programming language are
classes that are supplied with the
programming language so that
we can use in our programs
in the case that we need them and here
in this little graphic I have put you
four examples of predefined classes
that come in java and I tell you that I have
put only four examples but
come hundreds and hundreds that is to say to the
time to program in java us
we have hundreds and hundreds of classes
predefined that is already built
so that we can use them in
our programs if we need them
the examples that I have put in this
screen are the string class that
we have not seen it yet, it's good for
handle character strings strings
text the class more that is then the one that
let's see a little bit above in this
video which allows us to make the
mathematical calculations square roots
round powers and so on
the array class which is another one of those
we will manage throughout the course
the array class allows you to manipulate
handle arrays
arrays and then then we have the class
create that is another class that is used
quite when it comes to programming in java
and that allows
the concurrent programming that is called
but I've put four examples
of four of the most used classes
but as I say there are hundreds
so many are the classes that there are for
a programmer is impossible to memorize
all and not just memorize the
classes keep in mind that each class
predefined that comes with the language
java brings with it a number of methods
who perform different tasks with what
what if it is impossible to memorize all the
classes is even more impossible is to memorize
the methods that come with those classes
so that we can use them is because
what exists in java what is known
as a class library or
called api de java which is the pija
well, the blackboard is a library
where all the classes of the
java programming language and that all
programmer should consult with
often when preparing a
program since it is very likely that
example if you frequently use the
class more you forget it then some of
the methods that come within that
class you know that they exist but you do not
remember its syntax do not remember
of the arguments that come in that
method and you'll have to consult the
library
this library is very easy to use
to her and let's see an example I'll
open a browser for example firefox
previously
and once we open firefox firefox
sorry if you go to the google page
Well, in any search engine if you
you say to fix to fix that I do not
I have purple because the consultation with
often the first link that we
it offers then it is a link to the java app and
here it left library of classes not
so if we click on that link then
right now we have open what is the
java class library not yet
we are in a position to handle this
class library because this
class library you also have to
learn to manage it is composed of
different panels or parts that
we will talk about them at the time without
However good in this panel that
we have here below to the left then
they come in alphabetical order all the
classes that we currently have in the
java programming language and fixes
that as I told you there are one hundred 600 there is no
human person able to memorize all
these predefined classes that come with
the language so that we can
use
As I said before, there are classes that
commission calculations
mathematicians like most there are classes that
They are in charge of carrying out operations with
strings of characters like string there
classes because they are dedicated to work
with networks there are classes that are dedicated
to the graphic part for example having
here then green bay the youth good
all this refers to work
java graphic is to say if you want
create the graphical interface as you will have
that working with these classes here is
the same graphics class serves to
work with graphics in java graphics
from finally hundreds and hundreds of classes
Each class as I say has its own
methods and you will find out right now
those who did not know it before the
dimension of the programming language
java is to say the number of classes
predefined methods packages that already
We will see at the time what it is that
they come with this programming language
as of today, May 19, 2014 that
is when I'm recording this video the
app and it goes by version 7 what do you want
say this
well, it means that we
When installing a machine
virtual of the java
we've talked about it in videos
previous we are installing us the
version 7 with time then surely
that instead of installing version 7
we have to install version 8 and
in a couple of years with surely
let's be by version 9 by the version
10 is not to say the virtual machine of
java that we have installed in this course
It updates what the
update of the virtual machine
java because it consists of several things and a
of them is that more classes are included
that is, in this class library
right now the classes that exist are
these are the classes with which
We currently have to program in
Java
but over time new
you already know that information technology
evolves constantly and
programming languages also with what
what if a need arises
which requires the use of a calculation of a
class or whatever it is that right now
What you do is update the
java virtual machine instead of the
version 7 as they update it to 8 as
consequence the library is updated
of java classes is to say the api of
java is updated and include those classes
new ones that allow you to do these
news
that have been emerging over time is
the library of the left was fixed
constantly updated with which
There are many people who download it
because it is possible to download the
java library in local to have it
on your hard drive and well this download
Well, he's consulting it but I'm going
I recommend if you have an internet connection
it is to consult the online route because
If you consult online, you can be sure
that you're always updated
you know that java belongs to oracle with
which is good as the download or the
consultation is done from the page of
prayer said this
well then we go back to our
power Point presentation
and we already have a slight emotion of what
which is a predefined class not
worry that we will go deeper
course in the use of the sabín apa
api sorry or library of classes and in
this video what we are going to do is see
a little a little bit more the class more
because the class has a lot more
methods for doing mathematical calculations
and I'm just going to mention the
main calculations obviously if
you learn to use the class more for
do basic or usual calculations and
you also learn how to handle the api
java that we will see in future videos and
also already shortly
you will know how to use any method
belonging to the class plus or
belonging to any other kind of
java what methods are we going to see us from
the best class because the methods that
let's see from the matt class are more
point s qr t is to say the method s cub rt
what he does then is to return us a
decimal number
is the square root of the parameter
specified in parentheses in
definitive
point that is what is allowed
calculate the square root of a number
the method for what it does is calculate the
power of a number this method receives
two parameters or arguments a base and
an exponent
we are also going to use good this is not
we are going to use drinks or mentioned
more points and what it does is calculate the
sine of an angle plus a total what
does is calculate the tangent to so
the tangent arc is to say as you can
observe the class more
what it brings inside are diverse
srt methods all without cause so tan and
many others to do calculations not
round method what it does is round a
this number is used a lot is not
very frequent that the need arises
round one figure at the time of
work then in a java program and not
there is also the concept of constants
of class then we have already
seen what is a constant but we have
seen what is a constant itself is
say we have learned to declare a
constant in our own
we know that the value of a constant does not
can change as we have classes
own and predefined classes as per
example more we also have constants
own those that we have seen in videos
previous and predefined constants or
class constants
the constant predefined constants
of class are those that accompany the
class is to say they come with the class and what
what they do then is store in their
internal values that can not be
modified for example is very common
than to do trigonometry calculations
you need to use the number and then
the pi number because everyone I think we know
which is equal to 3 1416 rounding off
well, this is a fixed value
value of the number pi can not change
under no circumstances the number that
it has to be always the same is because
this reason why it is stored in
a constant constant that has
called and and as a consequence of this
we can use it and the type value
you can not change it a constant of
class
and all this as it translates to the
good practice then let's open
eclipse below and let's see
how to use the map class to perform
this series of basic calculations so
as always because we are going to close the
presentation of power point and we are going to
open the eclipse program
then then we go to the folder
where we have stored the program
we double click on the executable and
we wait for the program to load
you know it takes a few moments once
that the program loads well since it
usually open for the class you left
open is to say if at the time of closing
eclipse you left an open class like
is my case saved changes but
open is to say on the screen well
Eclipse is usually opened by that class
we remember that in the browser
packages because we have our project
which we call first steps
Within our project we have the
source src folder and inside we have
the default package something that is not yet
we know very well what is our
package and we have built at the moment
three classes well then let's build
a fourth class where we use the
best class because you know you can
leave open if you have the same as me
open class you can leave it open
because eclipse what it does is work
by tabs that is to say as you go
creating classes and leaving them
open as they appear
continuation of the previous
and if you want to work more
comfortable you can close the class from your
corresponding X and create a new
is to create a new class you know
what can be done from different
menus and buttons I'm going to use the
button on the toolbar and you
I'm going to say that this class is going to
call for example
calculations and a bass with more and I'm going to
say already to the creation window of
classes that create the main method and so
Well, we already have part of the work
done and then as always since we're going to
enter within the mail method no
this would be an example of the class itself
because it is a class that we have created
us right now and it's called
calculations commas well let's go to
use the sea class so you can see
what would be the mechanics
let's create a simple instruction
that allows us to find out the root
square of a number but I'm going to
do to start badly and I'm going to do it
bad so that you can see where the
error and see also how strict it is
the java programming language with the
data types then I will declare
an integer variable where
I intend to store the result of
the square root of a number then
Well I say int
then name of the variable
Well, I'm going to call you, for example, the root
we can call as we want and tell him
that this will be equal to more
point and then the method would come
but before putting the method that
we remember that to find the root it was s
qr t fix that eclipse it helps us
quite at the time of writing with these
menus of which we have spoken in
previous videos the behavior
smart when we put more
point a menu is displayed in which
all methods appear
that belong to the class plus all the
methods and also look at the impossible that
is to memorize this in addition to the methods
the constants also appear
predefined that come with marc and here
appears for example the constant and the
that we talked about a moment ago but
another number also appears
constant that is the number e that also
has a fixed value not good when
I put and I remove the zoom I'm going
but also notice that eclipse
offers us another help and is that
example if we are going to use that
qr t if now after the point
we write an s this menu is going to all
the methods that start with that and already
we are seeing in this menu well where
you find that q rte not
Well, if in addition to one you put a quota
we already have only the srt method and
here we are given a lot of information and
this makes it eclipse look at us
saying eclipse in this submenu that
appears on the right that you press the
Tab key to put the focus on
this window
what is the use of that window that we
informs this window good because this
window informs us of what it is that
does the method that does not have what
what to work with an editor of these
features like eclipse netbeans
etc. helps a lot at the time of
program it is also convenient
convenient I do not consider it
fundamental that when programming
in java you have always, although not what
we know use still minimized the
app and left the class library
a whole programmer java then
normally normally works with the
app and minimized because in this app and
also in the lower left window
we can arrive are ordered by order
alphabetical to the class more and when
let's see the class more notice that the
I'm seeing here if we click on it in
the window on the right so what we
appears from to press as it is a
very exhaustive information of what is it
who does this class and what is it for and
in addition all the methods belonging
to the class and well then what kind of
data returns how it is built
etcetera we are not yet in
willingness to understand this at all
you worry we will be working with it
little by little but well we also have
the help of the eclipse as we have seen
a moment ago if you look at this
menu that comes out in eclipse is us
saying that this method that q rt
receives a parameter or argument that
it has to be double type and this
appears here below informs us
of the type of data returned by this
method is to say this method what does
is to find the square root of a number
well that square root what
it has to be double it is to say it's a
double type data however if you
you see, I'm telling you that I
store the square root because still
we do not even have it done that we
store it in a whole type number
this is going to give an error because the method
s qr returns a double a decimal if
we tell you to keep it a whole not
it is possible with which if we finish
to complete
the square root for example 9
Well, this has to give us a
error notice that in this case eclipse
it will also do it to any other editor
Java programming does not emphasize the
red the instruction and we see a
information balloon to the left if
you place the mouse on top of that balloon
information because it tells us that there is a
Type conversion error and the case
is that you can not convert from double to
whole and that's because the method s qr you
what it does is return an integer if
you also set the internal parameter
It must be a double and we
however we have introduced an integer is
say in the help he told us the method
srt had to have here a double this
what the help told us and yet
the number that we have entered inside
of the arguments of this function is not
a double is an integer really what
is doing hub although we do not
let's see is to consider that number as
you see now on screen 90
we can also put for example the
square root of 952 this is
perfectly valid is a double the
error is that we can not
store it within a whole solution
I'm going to leave the 9 again, well, the
solution is to change the data type to
corresponding type is to say do not tell me
warehouses in a whole number but
they store it in a variable forgiveness or
in a number he stores it in a
variable of double type fixes that in
how much do we change the type of the variable
where we are storing the result
that you already know is 3
Well, automatically disappears
underlined red and the only thing that appears
now it is the information in yellow that
we have seen on other occasions for
tell us that that variable is not yet
used the only thing we would have to
do now it is because of the instruction
system or print
well print
root in the console and our program already
would be finished that is to say statement
variable initiation we are
starting at the square root of 9 and
then we tell him to print us in
the console the value you have stored
in the root variable if we execute this
program then in the console you have to
exit 3.0 and have to exit 3.0 the root
square of 9 stress because the result
that always returns this method is
a double with which if we click on the
play then look like in the console
after compiling it will take a
little does it effectively return a
3.0
Well, here you see the use of the class
plus
specifically with the srt method
let's leave this video at the point in
the one that we meet and in the next
video then we'll see how to use the
round method to round up we'll see how
also use the pop method
example to see then an example of
method that needs two parameters and
let's look at also see a concept
which is the recast concept is
change one type of data to another for that
as I say we will see in the next
delivery so as always I invite you to
Stay tuned for the next video
until then it goes well
Voir Plus de Vidéos Connexes
🚀 MÉTODOS CONSTRUCTORES y OBJETOS en JAVA | 🤔| POO con Java 🖥️ | Explicación FÁCIL 2023 | #4
🚀 CLASES ABSTRACTAS en JAVA | 🤔| Programación Orientada a Objetos 🖥️ | Explicación FÁCIL 2023 | #9
Curso Java. Estructuras principales III. Declaración variables Eclipse Vídeo 6
JAVA: Introducción a la Herencia ☕ DAM - DAW
🚀 HERENCIA en JAVA | 🤔| Programación Orientada a Objetos con Java 🖥️ | Explicación FÁCIL 2023 | #6
Curso Java. Anexos IV JTable II. Vídeo 268
5.0 / 5 (0 votes)