Wait.
>> What's wrong?
>> When did this turn into
a cooking show all of a sudden?
>> Since we had to talk about methods?
>> Care to explain, Rachael Ray?
>> [LAUGH] Well,
have you ever baked a cake before?
>> I have eaten a cake before.
>> Okay.
Well, then you're fully qualified for
this.
>> Okay.
>> All you have to do to bake
a cake is to put in flour, sugar.
>> The ingredients.
Okay.
>> The ingredients.
Yeah.
And then you follow
the instructions of the recipe.
>> Okay.
>> And then out comes a cake.
>> Like this?
>> Yeah.
>> Okay.
Well
connect the analogy to
the methods one more time.
>> Okay.
Sure so for
a method you can put in inputs.
>> Like we did the quantity for
the display method?
>> Yeah, and then you execute
the instructions of the method.
>> Okay, almost like the recipe for
making a cake?
>> Mm-hm.
Then you can have
the output value returned.
>> Outputs, they are delicious.
>> [LAUGH]
>> Let's look up more information
about input parameters for methods.
I'm going to do a Google search for
Jjava method parameter.
The first link looks good so
I'm going to click on it.
Now this article talks about
passing information to a method.
Here's a code snippet that computes
the monthly payments for a home loan.
It has four input parameters,
loan amount, interest rate, future value
of the loan, as well as the number
periods of the length of the loan.
And then inside this method we see
that we can use these input parameters
simply as variables to do
our math calculations.
When we call the compute payment method,
we have to make sure we pass in
the inputs in this specific order.
So the loan amount has to go first,
and then the rate and so on.
For the quiz in this section,
you'll have the chance to review
this article in more detail.
Within the main activity
of the desk Java app,
we're going to be modifying
the display quantity method and
the input parameter to
give you some practice.
Notice that in the decrement
method of our app,
what we call the display
quantity method,
we're passing the quantity variable
over as input to this method.
But the input parameter
is called 'number', so
whenever we want to refer to this input,
we just have to say number.
Now technically we could have used
the global quantity variable within this
method instead of passing
it as an input parameter.
but for the purposes of teaching
you about input parameters,
let's just leave it like this.
I can change this call to
the display quantity method so
it passes input, the number 30.
This is valid because it still
matches the input data type.
So in the decrement method when
we call it display quantity,
it will jump down here and
it will execute these instructions, and
the variable number will
have the value of 30.
I'll run it on my device to show you,
so now when I run the minus button on my
app, it will display
a quantity of 30 here.
So let me try that.
There.
And it actually happened like that.
I can also create a different variable
and pass that as an input to the method.
Here I've created a local variable
called some quantity, and
I initialized it to 100.
I passed this variable
as input to this method,
and now the number variable
inside here has a value of 100.
Let me run this on the device.
Now I expect when I hit the minus
button the quantity will update to 100.
And it does.
These are just some things
you can do to experiment with
passing in different inputs to a method.
As you work with input parameters,
another term that you might
come across is arguments.
When you call a method,
the inputs being passed to that
method are called the arguments.
Now this is kind of a funny word.
Because when you think of arguments,
you think of people yelling and
cursing at each other.
But this is not like that.
Arguments are simply the inputs
being passed to a method.
Input parameters are the actual
inputs in your method declaration and
those are the variables that
are used within your method.
So that's a slight difference between
input parameter and arguments.
In any case, go ahead and
read the article and
the instructor notes
about method parameters.
Then go ahead and
experiment with the code in your app.
First try to rename
the number input parameter
within the display quantity
method declaration.
Just simply give it
a different variable name.
Then go ahead and fix any errors,
and then run the app again.
For the next test, go ahead and
change the data type
of the number input parameter from
an int to something else like String.
Observe what happens and
then go ahead and undo the change.
If you want to experiment with
other things, go right ahead.
For example, if you have a question,
what would happen if I do x,
then just go ahead and try it.
إنتظري!
- ما هي المشكلة؟
- متى تحوّل هذا
إلى برنامج للطبخ فجأةً؟
- ألا يجب علينا أن نتكلم عن الطرق؟
- هل أنت مهتمة بالشرح، ريتشال راي؟
- حسناً
هل سبق لك أن خبزت كعكة من قبل؟
- لقد تناولت كعكة من قبل
- حسناً
حسناً، فأنت مؤهل تماماً
لذلك
- حسناً
- كل ما عليك القيام به لتخبز
كعكة هو وضع الدقيق والسكر
- المكونات
صحيح
- المكونات
نعم
ومن ثم تتبع
تعليمات الوصفة
-حسناً
- وبعد ذلك تُنجَز كعكة
- مثل هذا؟
- نعم
- حسناً
جيد
لنربط التشابه مع
الطرق مرة أخرى
- حسناً
بالتأكيد بتعاً
للطريقة يمكنك دخل الدخلات
- كما فعلنا بالـ quantity
من أجل طريقة العرض؟
- نعم، ثم نفّذنا
التعليمات التابعة للطريقة
- حسنا، تقريبا مثل وصفة لصنع الكعكة؟
- إممم
ثم يمكنك الحصول على
القيمة المعادة كخرج
- الخرج، إنها لذيذة
- دعنا نبحث عن معلومات أكثر
حول وسطاء الدخل للطريقة
سأقوم ببحث على الغوغل
لإيجاد "Java method parameter"
يبدو الرابط الأول جيد
لذلك سأقوم بالنقر عليه
الآن هذه المقالة تتحدث
عن تمرير المعلومات إلى الطريقة
وفيما يلي ملخص الكود والذي يحسب
الدفعات الشهرية لقرض منزل
يحتوي أربعة وسطاء دخل
loanAmount و interestRate وfutureValue
الخاصة بالقرض، كما هو الحال
لـ numberPeriods التي تعبر عن طول مدة القرض
ثم داخل هذه الطريقة نرى
أنه يمكننا استخدام وسطاء الدخل هذه
ببساطة كمتحولات للقيام
بالعمليات الحسابية
عندما نستدعي طريقة computePayment
فيجب علينا أن نتأكد من تمرير
الدخلات بهذا الترتيب المحدد
وبالتالي فيجب أن يأتي loanAmount أولاً
ومن ثم الـ rate وهكذا
لإختبار هذا القسم
سيكون لديك الفرصة لمراجعة
هذه المقالة بشيء من التفصيل
ضمن تطبيق
"MainActivity.Java"
سنقوم بتعديل
بطريقة dispalyQuantity
ووسيط الدخل
لتقوم ببعض التدريب
لاحظ أنه في طريقة
decrement ضمن تطبيقنا
بما سميّناه طريقة
dispalyQuantity
سنقوم بتمرير متحول quantity
هنا كدخل لهذه الطريقة
ولكن وسيط الدخل
يدعى number، لذلك
كلما أردنا أن نشير إلى هذا الدخل
علينا فقط أن نقول number
الآن من الناحية التقنية يمكننا استخدام
الـ quantity كمتحول عام ضمن هذه
الطريقة بدلاً من تمريره
على أنه وسيط دخل
ولكن لأغراض تعليمكم
حول وسطاء الدخل
دعونا نتركه بهذا الشكل
يمكنني تغيير هذه التسمية
لطريقة dispalyQuantity بحيث
تمرر الدخل، وهو الرقم 30
هذا صحيح لأنه لا يزال
يطابق مع نمط بيانات الدخل
حتى في طريقة decrement عندما
سميناها dispalyQuantity
سوف تقفز للأسفل هنا
وستتنفذ هذه التعليمات
سيأخذ المتحول number
قيمة الـ 30
سأشغله على جهازي لأريك
الآن وبعد أن أشغل زر الناقص في
تطبيقي، فإنه سيعرض
الكمية 30 هنا
لذلك دعوني أحاول ذلك
ها هو
وقد حصل هذا تماما بهذا الشكل
يمكنني أيضاً إنشاء متحول مختلف
وتمرير ذلك كدخل ضمن الطريقة
قمت هنا قمت بإنشاء متحول محلي
يدعى someQuantity
وقمت بتهيئته إلى 100
مررت هذا المتحول
كدخل ضمن هذه الطريقة
والآن متحول الـ number
داخل هذا المكان سيأخذ القيمة 100
دعوني أشغل هذا على الجهاز
الآن أنا أتوقع عند الضغط على زر
ناقص فإن quantity ستتحدث إلى 100
وهي كذلك
هذه ليست سوى بعض الأشياء
التي يمكنك القيام بها لتجربة
تمرير دخلات مختلفة ضمن الطريقة
وأنت تعمل مع وسطاء الدخل
هنالك فقرة أخرى من الممكن
أن تعترضك وهي الوسطاء
عند استدعائك للطريقة
فإن الدخلات التي مرت
ضمن تلك الطريقة تسمى وسطاء
الآن هذه كلمة مضحكة نوعاً ما
لأنه عندما تفكّر بالوسطاء
فإنك تعتقد أن الناس يصرخون
ويشتمون بعضهم الآخر
ولكن هذا ليس كذلك
إن وسطاء ببساطة هي دخلات
يتم تمريرها إلى الطريقة
وسطاء الدخل هي المدخلات
الفعلية ضمن تصريح الطريقة
وهذه هي المتحولات
المستخدمة ضمن طريقتنا
لذلك فإن الفرق بسيط جداً بين
وسيط الدخل و الوسطاء
في أي حال، تابع
وأقرأ المقالة
وملاحظات المدرب
حول وسطاء الطريقة
ثم تابع
وجرّب الكود ضمن تطبيقك
أولاً حاول إعادة تسمية
وسيط الدخل number
ضمن تصريح
طريقة displayQuantity
ببساطة إعطه
اسم متحول مختلف
ثم تابع وأصلح أي خطأ
وبعدها قم بتشغيل التطبيق مجدداً
للإختبار المقبل، تابع
وغيّر نمط البيانات
التابع لوسيط الدخل number
من النمط int إلى شيء آخر مثل String
راقب ماذا سيحدث
ومن ثم تابع وتراجع عن التغيير
إذا كنت ترغب في تجربة
أشياء أخرى، قم بها فوراً
على سبيل المثال، إذا كان لديك سؤال
ماذا سيحدث لو أني قمت بـ X
فقط تابع وجرب هذا
Wait.
>> What's wrong?
>> When did this turn into
a cooking show all of a sudden?
>> Since we had to talk about methods?
>> Care to explain, Rachael Ray?
>> [LAUGH] Well,
have you ever baked a cake before?
>> I have eaten a cake before.
>> Okay.
Well, then you're fully qualified for
this.
>> Okay.
>> All you have to do to bake
a cake is to put in flour, sugar.
>> The ingredients.
Okay.
>> The ingredients.
Yeah.
And then you follow
the instructions of the recipe.
>> Okay.
>> And then out comes a cake.
>> Like this?
>> Yeah.
>> Okay.
Well
connect the analogy to
the methods one more time.
>> Okay.
Sure so for
a method you can put in inputs.
>> Like we did the quantity for
the display method?
>> Yeah, and then you execute
the instructions of the method.
>> Okay, almost like the recipe for
making a cake?
>> Mm-hm.
Then you can have
the output value returned.
>> Outputs, they are delicious.
>> [LAUGH]
>> Let's look up more information
about input parameters for methods.
I'm going to do a Google search for
Jjava method parameter.
The first link looks good so
I'm going to click on it.
Now this article talks about
passing information to a method.
Here's a code snippet that computes
the monthly payments for a home loan.
It has four input parameters,
loan amount, interest rate, future value
of the loan, as well as the number
periods of the length of the loan.
And then inside this method we see
that we can use these input parameters
simply as variables to do
our math calculations.
When we call the compute payment method,
we have to make sure we pass in
the inputs in this specific order.
So the loan amount has to go first,
and then the rate and so on.
For the quiz in this section,
you'll have the chance to review
this article in more detail.
Within the main activity
of the desk Java app,
we're going to be modifying
the display quantity method and
the input parameter to
give you some practice.
Notice that in the decrement
method of our app,
what we call the display
quantity method,
we're passing the quantity variable
over as input to this method.
But the input parameter
is called 'number', so
whenever we want to refer to this input,
we just have to say number.
Now technically we could have used
the global quantity variable within this
method instead of passing
it as an input parameter.
but for the purposes of teaching
you about input parameters,
let's just leave it like this.
I can change this call to
the display quantity method so
it passes input, the number 30.
This is valid because it still
matches the input data type.
So in the decrement method when
we call it display quantity,
it will jump down here and
it will execute these instructions, and
the variable number will
have the value of 30.
I'll run it on my device to show you,
so now when I run the minus button on my
app, it will display
a quantity of 30 here.
So let me try that.
There.
And it actually happened like that.
I can also create a different variable
and pass that as an input to the method.
Here I've created a local variable
called some quantity, and
I initialized it to 100.
I passed this variable
as input to this method,
and now the number variable
inside here has a value of 100.
Let me run this on the device.
Now I expect when I hit the minus
button the quantity will update to 100.
And it does.
These are just some things
you can do to experiment with
passing in different inputs to a method.
As you work with input parameters,
another term that you might
come across is arguments.
When you call a method,
the inputs being passed to that
method are called the arguments.
Now this is kind of a funny word.
Because when you think of arguments,
you think of people yelling and
cursing at each other.
But this is not like that.
Arguments are simply the inputs
being passed to a method.
Input parameters are the actual
inputs in your method declaration and
those are the variables that
are used within your method.
So that's a slight difference between
input parameter and arguments.
In any case, go ahead and
read the article and
the instructor notes
about method parameters.
Then go ahead and
experiment with the code in your app.
First try to rename
the number input parameter
within the display quantity
method declaration.
Just simply give it
a different variable name.
Then go ahead and fix any errors,
and then run the app again.
For the next test, go ahead and
change the data type
of the number input parameter from
an int to something else like String.
Observe what happens and
then go ahead and undo the change.
If you want to experiment with
other things, go right ahead.
For example, if you have a question,
what would happen if I do x,
then just go ahead and try it.
- Espera.
- ¿Qué pasa?
¿Cuándo se transformó esto de repente
en un programa de cocina?
¿Desde que tuvimos que hablar de métodos?
¿Podrías explicarte, Rachael Ray?
Bueno, ¿has hecho alguna vez un pastel?
He comido pasteles.
- Entonces estás plenamente capacitado.
- Bueno.
Lo que tienes que hacer
para hornear un pastel
es agregar la harina, el azúcar...
- Los ingredientes.
- Los ingredientes. Sí.
Y luego sigues
las instrucciones de la receta.
Está bien.
Y luego sale un pastel.
¿Como este?
Sí.
Bueno, conecta la analogía
con los métodos una vez más.
Seguro. A un método
puedes aportarle las entradas.
¿Como hicimos con la cantidad
para el método display?
Sí, y luego ejecutas
las instrucciones del método.
Bien, ¿casi como la receta
para hacer un pastel?
Sï. Luego te devolverá
el valor de salida.
Las salidas son deliciosas.
Veamos más información
sobre los parámetros de entrada
para los métodos.
Voy a buscar en Google
java method parameter.
El primer enlace parece bueno
entonces haré clic en él.
Este artículo habla sobre
pasar información a un método.
Aquí hay un fragmento de código
que calcula pagos mensuales
de un préstamo hipotecario.
Tiene cuatro parámetros de entrada,
monto del préstamo, tasa de interés,
valor futuro del préstamo,
y la cantidad de períodos
de la duración del préstamo.
Luego dentro de este método
vemos que podemos usar
estos parámetros de entrada
simplemente como variables para hacer
nuestros cálculos matemáticos.
Cuando llamamos al método computePayment,
tenemos que asegurarnos
de pasarle las entradas
en este orden específico.
El monto del préstamo
va primero,
luego la tasa y así sucesivamente.
En el examen de esta sección,
podrás revisar este artículo
con más detalle.
Dentro de la MainActivity
del escritorio de aplicaciones Java,
modificaremos el método displayQuantity
y el parámetro de entrada
para que practiques un poco.
Observa que en el método decrement
de nuestra aplicación,
en el que llamamos
al método displayQuantity,
estamos pasando la variable quantity
como entrada de este método.
Pero el parámetro de entrada
se llama "number".
Así, cuando hagamos referencia
a esta entrada,
tenemos que decir number.
Técnicamente podríamos haber usado
la variable global quantity
dentro de este método en vez de pasarlo
como un parámetro de entrada .
Pero a fin de enseñarte
sobre los parámetros de entrada,
vamos a dejarlo así.
Puedo cambiar esta llamada
al método displayQuantity
para que pase como entrada, el número 30.
Esto es válido, ya que coincide
con el tipo de datos de entrada.
Así en el método decrement
cuando llamemos a displayQuantity,
saltará aquí y ejecutará
estas instrucciones,
y la variable number
tendrá el valor de 30.
Voy a ejecutarlo en mi dispositivo
para mostrarte.
Ahora cuando pulse el botón menos
en mi aplicación,
mostrará una cantidad de 30 aquí.
Voy a probarlo.
Y realmente sucedió así.
También puedo crear
una variable diferente
y pasarla como una entrada para el método.
Aquí he creado una variable local
llamada someQuantity
y la inicialicé en 100.
Pasé esta variable
como entrada de este método,
y ahora la variable number
aquí adentro tiene un valor de 100.
Ejecutaré esto en el dispositivo.
Ahora espero que cuando pulse
el botón menos
la cantidad
se actualice a 100.
Y lo hace.
Estas son solo algunas cosas
que puedes hacer para experimentar
pasando diferentes entradas a un método.
Al trabajar con parámetros de entrada,
otro término que podría surgir
es argumentos.
Cuando se llama a un método,
las entradas que se le pasan
se llaman argumentos.
Es una palabra un poco graciosa,
porque cuando hablamos de argumentos,
pensamos en gente
discutiendo y gritándose.
Pero aquí no es así.
Los argumentos son
solo las entradas
que se le pasan a un método.
Los parámetros de entrada
son las entradas reales
en la declaración del método
y esas son las variables
que se usan dentro del método.
Así que hay una leve diferencia
entre parámetros de entrada y argumentos.
Como sea, sigue adelante y lee el artículo
y las notas del instructor
sobre los parámetros del método.
Luego experimenta
con el código de tu aplicación.
Primero trata de cambiar el nombre
del parámetro de entrada number
dentro de la declaración
del método displayQuantity.
Simplemente ponle
un nombre de variable diferente.
Luego corrige cualquier error,
y ejecuta la aplicación de nuevo.
Para la prueba siguiente,
cambia el tipo de datos
del parámetro de entrada number
de int a otra cosa, tal como string.
Observa qué sucede
y luego deshaz el cambio.
Si quieres experimentar
con otras cosas, adelante.
Por ejemplo, si te preguntas
qué pasaría si hago x,
sigue adelante y pruébalo.
Wait.
Attendez.
>> What's wrong?
Qu'est-ce qu'il y a?
>> When did this turn into
a cooking show all of a sudden?
Depuis quand, soudain, celà c'est transformé en une émission culinaire?
>> Since we had to talk about methods?
Depuis que nous en avons
>> Care to explain, Rachael Ray?
Veuillez l'expliquer, Rachel Ray?
>> [LAUGH] Well,
have you ever baked a cake before?
[Sourire] Bien, avez-vous déjà préparé un gâteau auparavant?
>> I have eaten a cake before.
J'ai déjà mangé un gâteau auparavant.
>> Okay.
Okay.
Well, then you're fully qualified for
this.
Bien, dans ce vous êtes bien qualifié pour ceci.
>> Okay.
Okay.
>> All you have to do to bake
a cake is to put in flour, sugar.
Tout ce que vous avez à faire pour préparer un gâteau est d'ajouter à la farine, du sucre.
>> The ingredients.
Les ingrédients
Okay.
>> The ingredients.
Okay.>> Les ingrédients.
14
00:00:21,351 --> 00:00:22,210
Yeah.
ouais
And then you follow
the instructions of the recipe.
Puis vous suivez les instuctions de la recette.
>> Okay.
>> And then out comes a cake.
>> Ok.
>> Alors un gâteau est sorti.
>> Like this?
Comme celà?
>> Yeah.
Ouais.
>> Okay.
Well
Ok. Bien
connect the analogy to
the methods one more time.
Appliquer l'exemple à la méthode une fois de plus.
>> Okay.
Sure so for
Ok. Biensure
a method you can put in inputs.
une méthode que tu peux ajouter à l'entrée.
>> Like we did the quantity for
the display method?
comme nous l'avons fait la quantité pour la méthode afficheé?
>> Yeah, and then you execute
the instructions of the method.
Ouais, alors vous exécutez les intructions de la méthode.
>> Okay, almost like the recipe for
making a cake?
Ok, de la même façon que la recette pour préparer le gâteau?
>> Mm-hm.
Mm-hm.
Then you can have
the output value returned.
Alors vous avez une valeur en retour.
>> Outputs, they are delicious.
Resultats, ils sont délicieux.
>> [LAUGH]
>> Let's look up more information
>> [SOURIRE]>> Allons chercher plus d'informations
about input parameters for methods.
sur les paramètres d'entrée pour les méthodes.
I'm going to do a Google search for
Jjava method parameter.
Je vais une recherche sur Google concernant paramètre de la méthode Jjava.
32
00:01:01,460 --> 00:01:04,250
The first link looks good so
I'm going to click on it.
Le premier lien semble bien alors je vais cliquer dessus.
Now this article talks about
passing information to a method.
Maintenant que cet article par le passer des informations à une méthode.
Here's a code snippet that computes
the monthly payments for a home loan.
Voici un extrait de code qui calcule les paiements mensuels pour un prêt immobilier.
It has four input parameters,
loan amount, interest rate, future value
Il a quatre paramètres d'entrée, montant du prêt, taux d'intérêt, valeur future
of the loan, as well as the number
periods of the length of the loan.
de l'emprunt, ainsi que le nombre de périodes de la durée du prêt.
And then inside this method we see
that we can use these input parameters
Et puis, Dans cette méthode, nous voyons que nous pouvons utiliser ces paramètres d'entrée
simply as variables to do
our math calculations.
tout simplement en tant que variables à faire nos calculs mathématiques.
When we call the compute payment method,
Quand nous appelons la méthode de paiement compute,
we have to make sure we pass in
the inputs in this specific order.
Nous devons veiller à ce que nous passons aux entrées dans cet ordre précis.
So the loan amount has to go first,
and then the rate and so on.
Donc, le montant du prêt doit être passé en premier, et puis le taux et ainsi de suite.
For the quiz in this section,
Pour le quiz dans cette section,
you'll have the chance to review
this article in more detail.
vous aurez la chance de revoir cet article plus en détail.
Within the main activity
of the desk Java app,
Au sein de l'activité principale de l'application Java de bureau,
we're going to be modifying
the display quantity method and
Nous allons modifier l'affichage de la méthode de quantité et
the input parameter to
give you some practice.
le paramètre d'entrée pour vous donner une certaine pratique.
Notice that in the decrement
method of our app,
Notez que dans la méthode décrémentation de notre application,
what we call the display
quantity method,
ce que nous appelons méthode d'affichage de la quantité,
we're passing the quantity variable
over as input to this method.
Nous transmettons la variable quantité comme entrée dans cette méthode.
But the input parameter
is called 'number', so
Mais le paramètre d'entrée est appelé « numéro », donc
whenever we want to refer to this input,
we just have to say number.
chaque fois que nous voulons voir à cette entrée, il suffit de dire le numéro.
Now technically we could have used
the global quantity variable within this
Maintenant techniquement nous aurions pu utiliser la variable quantité globale au sein de cette
method instead of passing
it as an input parameter.
méthode au lieu de le passer comme paramètre d'entrée.
but for the purposes of teaching
you about input parameters,
mais l'objectif de cet est de vous parler des paramètres d'entrée,
let's just leave it like this.
Laissons le simplement comme ça.
I can change this call to
the display quantity method so
Je peux changer cet appel à la méthode d'affichage quantité ainsi
it passes input, the number 30.
elle passe l'entrée, le nombre 30.
This is valid because it still
matches the input data type.
Ceci est valable parce qu'il correspond encore au type de données d'entrée.
So in the decrement method when
we call it display quantity,
Dans la méthode de dimunition lorsque nous faisons appel il affichage la quantité,
it will jump down here and
it will execute these instructions, and
il sautera ici-bas et Il va exécuter ces instructions, et
the variable number will
have the value of 30.
le variable numéro aura la valeur 30
I'll run it on my device to show you,
so now when I run the minus button on my
Je vais le lance sur mon appareil pour vous montrer, maintenant quand je lance le bouton "-" de mon
app, it will display
a quantity of 30 here.
application, il affichera une quantité de 30 ici.
So let me try that.
Alors laissez-moi l'essayer.
There.
And it actually happened like that.
Là. Et il s'est réellement passé comme ça.
I can also create a different variable
and pass that as an input to the method.
Je peux aussi créer une variable différente et le passer comme une entrée à la méthode.
Here I've created a local variable
called some quantity, and
Ici, j'ai créé une variable locale appelé une quantité, et
I initialized it to 100.
Je l'ai initialisé à 100.
I passed this variable
as input to this method,
J'ai passé cette variable en tant qu'entrée à cette méthode,
and now the number variable
inside here has a value of 100.
et maintenant la variable nombre a à l'intérieur une valeur de 100.
Let me run this on the device.
Je l'exécute sur l'appareil.
Now I expect when I hit the minus
button the quantity will update to 100.
Maintenant, quand je presse le bouton négatif, je m'attend à ce que la quantité se changera à 100.
And it does.
These are just some things
you can do to experiment with
Ce sont certaines choses que vous pouvez faire pour l'expérimenter
passing in different inputs to a method.
en passant différents entrées à une méthode.
As you work with input parameters,
En travaillant avec des paramètres d'entrée,
another term that you might
come across is arguments.
un autre terme que vous pourriez croiser est arguments.
When you call a method,
Lorsque vous appel à une méthode,
the inputs being passed to that
method are called the arguments.
les entrées passées à cette méthode sont appelés les arguments.
Now this is kind of a funny word.
Maintenant, c'est un drôle de mot.
Because when you think of arguments,
you think of people yelling and
Parce que quand vous pensez à des arguments, vous voyez des gens qui crient et
cursing at each other.
maudissant l'un l'autre.
83
00:03:32,510 --> 00:03:34,310
But this is not like that.
Mais ce n'est pas comme ça.
Arguments are simply the inputs
being passed to a method.
Les arguments sont tout simplement les entrées d'une méthode.
Input parameters are the actual
inputs in your method declaration and
Paramètres d'entrées sont les entrées déclarées de votre méthode et
So that's a slight difference between
input parameter and arguments.
Voilà donc une légère différence entre paramètre d'entrée et des arguments.
In any case, go ahead and
read the article and
En tout cas, allez et lisezz l'article et
the instructor notes
about method parameters.
les notes de l'instructeur sur les paramètres de la méthode.
Then go ahead and
experiment with the code in your app.
Puis allez et expérimenter le code dans votre application.
First try to rename
the number input parameter
Tout d'abord, essayez de renommer le nombre du paramètre
within the display quantity
method declaration.
de la déclaration de la quantité de la méthoded'affichage.
93
00:04:01,380 --> 00:04:03,850
Just simply give it
a different variable name.
Simplement donner lui un nom de variable différent.
Then go ahead and fix any errors,
and then run the app again.
Alors allez-y et corriger les erreurs, puis exécutez l'application à nouveau.
For the next test, go ahead and
change the data type
Pour le prochain test, aller et modifier le type de données
of the number input parameter from
an int to something else like String.
du paramètre d'entrée numéro de entier à autre chose comme chaîne de caractère.
Observe what happens and
then go ahead and undo the change.
Observer ce qui se passe puis allez et annuler la modification.
If you want to experiment with
other things, go right ahead.
Si vous voulez expérimenter avec d'autre choses, allez-y.
For example, if you have a question,
Par exemple, si vous avez une question,
what would happen if I do x,
then just go ahead and try it.
que se passerait-il si je fais x, alors aller et l'essayer.
Tunggu.
Ada apa?
Kapan pembicaraan ini tiba-tiba berubah
menjadi acara memasak?
Sejak kita membahas metode?
Bisa jelaskan, Rachael Ray?
[TERTAWA] baiklah,
apakah kamu pernah memanggang kue?
Saya pernah makan kue.
Baik.
Baiklah, saya akan jelaskan.
Baik.
Untuk memanggang kue,
masukkan tepung, gula.
Bahan-bahannya.
Ya.
Bahan-bahannya.
Ya.
Kemudian, ikuti petunjuk resep.
Oke.
Dan kemudian, kue sudah jadi.
Seperti ini?
Ya.
Oke.
Baiklah,
coba hubungkan analogi
dengan metode sekali lagi.
Oke.
Tentu saja,
metode di mana kamu dapat
memasukkan masukan.
Seperti yang kita lakukan dengan
kuantitas untuk metode tampilan?
Ya, kemudian kamu melaksanakan
petunjuk metode.
Oke, hampir sama seperti
resep membuat kue?
Mm-hm.
Kemudian kamu mendapatkan nilai keluaran.
Keluaran, sangat lezat.
[TERTAWA] >> Mari kita
perhatikan lebih banyak informasi
mengenai parameter masukan untuk metode.
Saya akan melakukan pencarian Google
untuk parameter metode Java.
Tautan pertama tampak bagus,
jadi saya akan mengeklik tautan ini.
Sekarang, artikel ini membahas tentang
memberikan informasi pada suatu metode.
Ini adalah potongan kode yang mengkomputasi
pembayaran bulanan untuk kredit rumah.
Ada empat parameter masukan, jumlah
pinjaman, suku bunga, nilai masa depan
pinjaman, dan jumlah
periode panjang pinjaman.
Kemudian, dalam metode tersebut, kita dapat
menggunakan parameter masukan tersebut
sebagai variabel untuk melakukan
penghitungan matematika.
Ketika kita menggunakan
metode pembayaran komputasi,
kita harus memastikan
bahwa masukan sudah
dimasukkan dengan urutan
khusus seperti ini.
Jadi, jumlah pinjaman pada urutan pertama,
kemudian suku bunga dan seterusnya.
Untuk kuis pada bagian ini,
Anda memiliki kesempatan untuk
mereview artikel ini secara rinci.
Dalam kegiatan utama
aplikasi Java meja,
kita akan mengubah
metode kuantitas tampilan dan
parameter masukan untuk
memberikan Anda latihan.
Perhatikan bahwa metode
susutan aplikasi
yang kami sebut sebagai
metode kuantitas tampilan,
kita memasukkan variabel kuantitas
sebagai masukan untuk metode ini.
Tapi parameter masukkan
disebut 'jumlah', jadi
kapanpun kita ingin mengacu pada
masukan ini, sebut saja jumlah.
Secara teknis, kita dapat menggunakan
variabel kuantitas global dalam
metode selain memasukkannya
sebagai parameter masukan,
namun, untuk mengajari Anda
tentang parameter masukan,
mari kita biarkan seperti ini.
Saya bisa mengubah penggunaan ini untuk
metode kuantitas tampilan, sehingga
inii memasukkan masukan, jumlah 30.
Hal ini benar karena masih cocok
dengan jenis data masukan.
Jadi, pada metode susutan, ketika
kita menyebutnya kuantitas tampilan,
Ini akan melompat di sini dan
melakukan instruksi tersebut, dan
jumlah variabel akan memiliki nilai 30.
Saya akan menjalankannya
di perangkat saya untuk
menunjukkan kepada Anda. Ketika
saya menekan tombol minus
pada aplikasi, kuantitas 30 ditampilkan.
Saya akan mencobanya.
Lihat.
Seperti inilah yang terjadi.
Saya juga dapat membuat
variabel lainnya dan
memasukkannya sebagai
masukan untuk metode.
Di sini, saya telah membuat variabel lokal
yang disebut beberapa kuantitas, dan
saya beri inisial 100.
Saya memasukkan variabel ini
sebagai masukan untuk metode.
Dan sekarang variabel jumlah di
dalam sini memiliki nilai 100.
Saya akan mencobanya pada perangkat.
Sekarang, saya harap
ketika saya menekan tombol
minus, kuantitasnya akan
berubah menjadi 100.
Dan berhasil.
Ada beberapa hal yang
dapat Anda coba dengan
memasukkan masukan yang
berbeda pada metode.
Sembari mengerjakan parameter masukan,
istilah lainnya yang dapat
muncul adalah argumen.
Ketika Anda menggunakan suatu metode,
masukkan yang dimasukkan pada metode
tersebut disebut sebagai argumen.
Kedengarannya seperti kata yang lucu.
Karena ketika Anda mendengar
kata argumen, Anda
pasti membayangkan orang
yang saling berteriak
dan memaki-maki.
Tidak seperti itu.
Argumen adalah masukan yang
dimasukkan pada metode.
Parameter masukan adalah masukan
aktual pada pernyataan metode Anda dan
merupakan variabel yang
digunakan dalam metode Anda.
Sehingga, terdapat perbedaan kecil
antara parameter masukan dan argumen.
Namun, lanjutkan saja
dan baca artikel dan
catatan instruktur
mengenai parameter metode.
Lalu lanjutkan dan lakukan percobaan
dengan kode pada aplikasi Anda.
Pertama, coba ubah nama
parameter masukan jumlah
dalam pernyataan metode
kuantitas tampilan.
Beri nama variabel yang berbeda.
Lalu lanjutkan dan perbaiki kesalahan,
dan jalankan aplikasi lagi.
Untuk pengujian berikutnya,
lanjutkan dan ubah jenis data
parameter masukan jumlah dari
int menjadi sesuatu seperti String.
Lihat yang terjadi dan kemudian
lanjutkan dan batalkan perubahan.
Jika Anda ingin mencoba hal
lainnya, lakukan saja.
Misalnya, jika Anda
mempunyai pertanyaan,
apa yang terjadi jika saya melakukan
x, lakukan saja dan coba.
ちょっと待って。
>> どうしたの?
>> いつからクッキングショーになったの?
>> それはメソッドを学ぶためよ。
>> レイチェル・レイさん、説明してもらえるかな?
>> ケーキをつくったことはある?
>> 食べたことはあるよ。
>> じゃあ
これはあなたにぴったりだと思うわ
>> そうなんだ。
>> ケーキは小麦粉と砂糖を入れれば作れるのよ。
>> 材料だね。
分かった。
>>そう材料。
その通り。
そしてレシピにしたがうだけよ。
>> わかった。>>それでケーキができるんだね。
>> こんな感じ?
>> そう。
>> わかった。
これとメソッドとどんな関係があの?
>> それは、
メソッドにはインプットがあるわ。
>> displayメソッドのquantity見たいにかい?
>> そう、そしてメソッドに従って実行するの。
>> 分かった、ケーキのレシピに従うようにだね?
>> その通り。
そしてアウトプットを受け取ることができるの。
>> アウトプットっておいしいんだね。
>> メソッドのインプットパラメータについて
もっと学んでみましょう
JavaメソッドのパラメータをGoogleで検索してみます。
最初のリンクがよさそうですね。
メソッドに情報を渡すことについて書いてあります。
これは住宅ローンの月額を計算するコードです。
4つのインプットがあり、ローンの額、利子、将来額、
そしてローンの期間です。
メソッドの中では、そのインプットが計算をするために
変数として使われています。
computePaymentメソッドを呼ぶ時には、
インプットをこの順番に渡すことが肝心です。
ローンの額、利子、というように記入します。
今回の問題では、
これを詳細に読むことになります。
Just JavaアプリのMainActivityの中で、
displayQuantityメソッドとそのインプットを変更して、
練習をしてみたいと思います。
アプリのdecrementメソッドでは、
displayQuantityメソッドを呼ぶときに、
quantityという変数を渡していることに注目してください。
インプットパラメータはnumberとなっています。
このインプットを使いたいときには、numberを
使わなければいけません。
ここで、インプットパラメータを使わずに、
quantityというグローバル変数を
使うこともできます。
しかし、インプットパラメータを学ぶために、
このままにしておきましょう。
このdisplayMethodのコールを
30という数字を渡すように変更します。
これはインプットのタイプと合っているので大丈夫です。
decrementメソッドでdisplayQuantityメソッドを呼ぶと、
ここにきて、この指令を実行します。
ここで変数は30になります。
端末で実行してみます。マイナスボタンを押すと、
30という料を表示します。
やってみましょう。
ちゃんと機能していますね。
もう一つ編巣を作って、それを渡すこともできます。
ここにローカル変数を作って、
100としました。
この変数をメソッドのインプットとして記入します。
これでnumber変数は100となりました。
マイナスボタンを押すと、100となるはずです。
ちゃんと機能していますね。
メソッドのインプットを渡す練習のために、
このようなことを試してみてもいいでしょう。
インプットパラメータを扱ううえで、
耳にするもう一つの単語はargumentです。
メソッドを呼ぶとき、
そのメソッドに渡されるインプットは、argumentといいます。
少しおかしな単語なんですが、
argumentと聞くと、なにか口論している
イメージが湧きますよね。
でもこれは違います。
argumentは単純にメソッドに渡されるインプットです。
インプットパラメータはメソッドの宣言で使われるもので、
メソッドの中で使われる変数です。
なので、インプットパラメータとargumentは少し違います。
それでは、メソッドのパラメータについて、この記事と、
指導書を読んでみてください。
そして自分のアプリで試してみてください。
まずdisplayQuantityメソッドの中で、
numberというインプットパラメータを変えてください。
違う変数の名前を与えてください。
そしてエラーを解消して、実行してみてください。
次のテキストでは、numberインプットパラメータのタイプを
intから、例えばstringなど違ったタイプにしてみてください。
何が起こるかを見て、元に戻してください。
他にも試したいことがあればぜひやってみてください。
これをしたらどうなるだろう、と思ったら、
それを試してみてください。
잠깐만요.
>> 무슨 일이예요?
>> 우리, 언제부터
요리 프로그램을 하고 있는 거죠?
>> 메소드에 관한 얘기 할 때부터?
>> Rachael Ray씨, 설명 좀 해주시죠?
>> [LAUGH] 음,
케이크 구워 본 적 있으세요?
>> 먹어본 적이야 있죠.
>> 알겠어요.
그럼, 자격은 충분해요.
>> 좋아요.
>> 케이크를 구우려면
밀가루, 설탕을 넣기만 하면 되요.
>> 재료들 말이죠.
좋아요.
>> 네, 재료요.
예.
그리고 레시피에 나온 대로
따라가는 거죠.
>> 좋아요.
>> 그러면 케이크가 되는 거예요.
>> 이렇게요?
>> 그래요.
>> 좋아요.
음,
이 비유를 메소드에 다시 한 번만
연결해 설명해 주세요.
>> 좋아요.
메소드를 만들려면
입력을 해야 하잖아요.
>> 디스플레이 메소드에
수량값을 넣은 것처럼 말이죠?
>> 그래요, 그리고 나서
메소드의 명령을 수행하는 거예요.
>> 알겠어요, 그러니까 케이크를
굽기 위한 레시피처럼 말이죠?
>> 으-흠.
그러면 출력이
리턴값으로 나오는 거죠.
>> 출력이라, 맛있네요.
>> [LAUGH]
>> 메소드에 들어가는
입력 파라미터에 대해 더 알아보죠.
자바 메소드 파라미터에 대해
구글 검색을 해볼께요.
처음 나온 링크가 괜찮아 보이네요.
클릭해보죠.
이 글은 메소드에 정보를 전달하는
법에 관한 내용이군요.
여기 나온 짧은 코드는 주택 융자금
상환 월부금 계산을 하는 건데요.
입력 파라미터가 4개 있군요.
상환금액, 이자율, 융자금 미래가치,
그리고 융자 상환 기간 수치입니다.
이 메소드를 보시면
이 입력 파라미터를 변수로 사용해서
계산을 할 수 있음을 알 수 있습니다.
상환금 계산 메소드를 호출하면,
이 정확한 순서대로 입력해야 합니다.
맨 처음이 상환금액이고 그 다음이
이자율, 이런 식으로 말이죠.
이 파트에 낸 퀴즈를 풀려면,
이 글 전체를 자세히 읽어보시는 게
좋을 겁니다.
데스크 자바 앱의
메인 액티비티 상에서,
수량 디스플레이 메소드와
입력 파라미터를 수정해서
여러분에게 실습할 수 있는
기회를 드릴 거예요.
우리 앱에서 디스플레이 수량
메소드라고 부르는 감소 메소드에선
48
00:01:52,680 --> 00:01:54,880
이 메소드에 수량 변수를
입력한다는 사실을 기억하세요.
하지만 입력 패러미터 이름이
'number'이므로
이 입력치를 가리킬 때 역시
number라고 지칭해 주어야 합니다.
기술적으로는,
입력 파라미터로 전달하는 대신에
이 메소드 내의 글로벌 수량 변수를
사용할 수도 있습니다.
하지만 여러분께 입력 파라미터에 대해
알려드리는 게 목적이기 때문에,
그냥 이대로 두기로 하죠.
이 호출문을
디스플레이 수량 메소드로 바꿔
숫자 30을
입력으로 전달할 수 있습니다.
입력 데이터 타입에 부합하므로
이렇게 해도 괜찮습니다.
디스플레이 수량이라 부르는
이 감소 메소드에서는,
이 쪽 아래로 점프해서
이 명령들을 수행한 후에
변수 수치가 30이 되는 것입니다.
이걸 제 기기에서 작동시켜 보여드리죠.
앱에서 마이너스 버튼을 누르면
여기에 30이라는 수량이 표시됩니다.
한 번 해보죠.
여기 보이시죠.
실제로는 이렇게 해서 나오는 수치입니다.
다른 변수를 만들어서 이를 메소드에
입력할 수도 있습니다.
여기에 some quantity라는
로컬 변수를 만들었어요. 그리고
100으로 초기화했습니다.
이 변수를 메소드에
입력치로 전달했어요.
이제 이 안에 있는 수치 변수값이
100이 되었습니다.
기기에서 작동해 보죠.
마이너스 버튼을 누르면 수량이
100으로 업데이트 될 겁니다.
보시는 대로요.
여기 있는 것들은
입력치를 달리해서
메소드에 시험 삼아
전달해 보실 수 있어요.
입력 파라미터를 사용하다 보면,
아규먼트(argument)라는 용어를
접하게 되실 겁니다.
메소드를 호출할 때,
전달되는 입력치를
아규먼트라고 합니다.
어찌 보면 재미있는 표현이죠.
아규먼트라는 말을 생각해 보면,
사람들이 소리지르거나 서로한테
욕하는 장면이 떠오르잖아요.
하지만 여기서는 아닙니다.
아규먼트란 단순히 메소드에 전달되는
입력치를 뜻하는 용어니까요.
입력 파라미터는 메소드 선언에
들어가는 실제 입력이며
메소드 안에서 사용하는 변수입니다.
따라서 입력 파라미터와 아규먼트는
약간의 차이가 있는 것이죠.
어쨌든 글을 계속 읽어보죠.
작성자는 여기서
메소드 파라미터에 관해
언급하고 있는데요.
해당 코드를 여러분 앱으로 한번
실험해 보세요.
먼저 number라는 이름을
디스플레이 수량 메소드 선언에 있는
92
00:03:58,650 --> 00:04:01,380
입력 파라미터로 바꿔 보세요.
변수명만 바꿔 주면 됩니다.
그리고 에러 발생시 이를 수정하고
앱에서 작동시켜 보세요.
다음 테스트는, 입력 파라미터 수치의
데이터 종류를 바꿔보는 겁니다.
int에서 String 같이 말이죠.
그러면 어떻게 되는지 확인해본 후
바꿨던 내용을 원래대로 되돌리세요.
다른 걸로도 시험해보고 싶으시다면
얼마든지 좋습니다.
예를 들어, 이러이러하게 해보면
어떻게 될지가 궁금하시다면
망설이지 말고 직접 해보세요.
Espera.
O que houve?
Quando isso virou um programa
culinário de repente?
Desde que começamos a falar sobre métodos.
Pode explicar, Ana Maria Braga?
Bem, você já fez um bolo alguma vez?
Eu já comi!
Certo.
Então está qualificado para isso.
Certo.
Tudo o que você precisa fazer para assar
um bolo é misturar farinha, açúcar...
- Os ingredientes.
- Isso, os ingredientes.
E então você segue as
instruções da receita.
- Certo.
- E então vira um bolo.
Como esse?
Sim.
Certo.
Conectando a analogia
aos métodos mais uma vez.
Então para um método você
coloca entradas.
Como fizemos a quantidade
para o método de exibição?
Isso, e então você executa
as instruções do método.
Certo, quase igual a receita
para fazer um bolo?
Isso!
Então você tem retornados
os valores de saída.
Valores de saída, são deliciosos.
Vamos procurar mais informações
sobre parâmetros de entrada para métodos.
Vou fazer uma pesquisa para
"parâmetros métodos Java".
O primeiro link parece bom,
então vou clicar nele.
Agora esse artigo fala sobre
como passar informação para um método.
Aqui uma parte do código que calcula
o pagamento mensal de um empréstimo.
Ele tem quatro parâmetros de entrada:
valor do empréstimo, taxa de juros,
valor futuro do empréstimo, assim como
os meses de duração do empréstimo.
E então, dentro desse método, nós vemos
que podemos usar esses parâmetros
como variáveis para
fazer nossas contas.
Quando chamamos o método
de pagamento computado,
temos que ter certeza que colocamos
as entradas nessa ordem específica.
O total do empréstimo tem que vir primeiro
e depois a taxa e assim por diante.
Nos exercícios dessa sessão,
você vai ter a chance de rever
esse artigo mais detalhadamente.
Dentro da atividade principal
do aplicativo Just Java
nós vamos modificar o método
de exibição de quantidade
e o parâmetro de entrada para
que você possa praticar.
Observe que no método de decréscimo
do nosso aplicativo,
que quando chamamos o método
de exibição da quantidade
estamos mudando a variável de quantidade
em uma entrada nesse método.
Mas o parâmetro de entrada
é chamado number, então
sempre que queremos nos referir a essa
entrada, só devemos escrever number.
Agora tecnicamente, nós poderíamos
ter usado a quantidade global da variável
neste método ao invés de passá-lo
como um parâmetro de entrada,
mas com o propósito de ensinar você
sobre parâmetros de entrada,
vamos deixar assim.
Eu posso mudar essa chamada
para o método de exibição de quantidade
para que passe a entrada, o número 30.
Isso é válido porque ainda corresponde
aos tipo de dados de entrada.
Então no método de decréscimo
quando chamamos displayQuantity
vai pular para cá e executar
essas instruções,
e o número da variável terá o valor 30.
Vou rodar no meu dispositivo para mostrar,
então quando eu rodar o botão "menos"
no meu aplicativo, vai aparecer
uma quantidade de 30 aqui.
Então deixe eu tentar.
Pronto.
E realmente aconteceu isso.
Também posso criar uma variável diferente,
e colocar como uma entrada para o método.
Aqui eu criei uma variável local,
chamei uma quantidade
e iniciei em 100.
Passei essa variável
como entrada para este método,
e agora o número da variável
aqui tem um valor de 100.
Deixe-me mostrar no dispositivo.
Agora quando eu pressiono o menos,
eu espero que a quantidade seja 100.
E dá certo.
Essas são só algumas coisas
que pode fazer para experimentar,
passando diferentes entradas
para um método.
Enquanto você trabalha
com parâmetros de entrada,
outro termo que pode
surgir são argumentos.
Quando você chama um método,
as entradas sendo passadas para aquele
método são chamadas de argumentos.
É uma palavra engraçada.
Porque quando pensa em argumentos,
você pensa em pessoas gritando
e se ofendendo.
Mas isso não é assim.
Argumentos são simplesmente entradas
sendo passadas para um método.
Parâmetros de entrada são as verdadeiras
entradas na sua declaração de método
e aquelas são as variáveis que serão
usadas dentro do método.
Então tem uma pequena diferença entre
parâmetro de entrada e argumentos.
De qualquer forma, continue
e leia o artigo,
e as notas do instrutor sobre
parâmetros de um método.
Então experimente com
o código em seu aplicativo.
Primeiro, tente renomear
o parâmetro de entrada "numero"
dentro da declaração
do método de exibição de quantidade.
Simplesmente coloque
um nome diferente na variável.
Então vá adiante, resolva qualquer erro,
e então rode o aplicativo de novo.
Para o próximo teste, vá em frente
e mude o tipo de dado
do parâmetro de entrada de número
de uma int para algo como uma String.
Observe o que acontece e então
desfaça a mudança.
Se quiser experimentar em outros,
fique a vontade.
Por exemplo, se tem uma dúvida,
sobre o que aconteceria se mudasse
algo vá em frente e teste.
Подожди.
>> Что не так?
>> Как это мы вдруг оказались
в кулинарном шоу?
>> Потому что нам нужно
было поговориьт о методах?
>> Может объяснишь, Рейчел Рэй?
>> Ну, ты когда-нибудь
раньше пек пироги?
>> Я их раньше ел.
>> Ладно.
Что ж, да ты профессионал.
>> Ага.
>> Чтобы испечь пирог, тебе лишь
нужно взять муку, сахар.
>> Ингредиенты.
>> Ингредиенты.
Да.
А потом выполняй инструкции рецепта.
>> Ладно.
>> И потом появится пирог.
>> Вот так?
>> Да.
>> Ага.
Что ж,
свяжи эту аналогию с методом еще раз.
>> Хорошо. Конечно.
Для метода нужно ввести
входные значения.
>> Как мы делали с переменной
quantity для метода display?
>> Да, а потом ты выполняешь
инструкции метода.
>> Ага, почти как рецепт
для выпечки пирога.
>> Угу. Тогда
ты получишь возвращенную
выходную величину.
>> Выходные величины такие вкусные.
>> Найдем побольше информации
о входных параметрах для методов.
Я задам в Google поиск параметра
Java метода.
Первая ссылка мне нравится,
я на нее нажму.
Эта статья рассказывает о
введении информации в метод.
Вот фрагмент программы, которая
вычисляет месячную плату за съем дома
В ней четыре входных параметра: сумма
аренды, процент, будущая стоимость
аренды и еще количество периодов
долговременности съема.
А внутри этого метода видим что можно
использовать эти входные параметры
просто как переменные, чтобы сделать
математические расчеты.
Когда мы вызываем
метод computeРayment,
мы должны убедиться, что вводим
входные данные в определенном порядке
Так что сначала идет сумма аренды,
потом процент и так далее.
Чтобы сделать тест этого раздела,
у вас будет возможность посмотреть
эту статью подробнее.
В МainАctivity в приложении Just Java
мы будем изменять метод
displayQuantity и
входной параметр, чтобы
вы попрактиковались.
Обратите внимание, что в методе
уменьшения на единицу в приложении
или что мы зовем
методом displayQuantity,
мы вводим переменную quantity как
входное значение в этот метод.
Но входной параметр называется
number, так что когда
мы захотим сослаться на это входное
значение, нам надо сказать number.
Технически, мы могли бы использовать
глобальную переменную quantityв
этом методе вместо того, чтобы
выдавать ее за входной параметр.
Но ради того, чтобы учить
вас о входных параметрах,
давайте оставим их как есть.
Я могу изменить эот вызов на
метод displayQuantity, так что
он вводит входное значение, число 30.
Это допустимо, потому что по-прежнему
сопоставимо с типом входных данных.
Таким образом,когда мы вызываем
displayQuantity, в методе
уменьшения, он прыгнет вниз,
сюда, и выполнит эти инструкции.
А переменная number будет
иметь значение 30. Я запущу это
на своем телефоне и покажу вам.
Теперь, когда я жу кнопку минус на
приложении, оно показывает
количество 30.
Сейчас я попробую.
Вот.
Так оно и получилось.
Я могу создавать различные переменные
вводить их как входные данные в метод
Вот, я создала локальную переменную
под названиемsomeQuantity и
присвоила ей значение 100.
Я ввела эту переменную как входную
величину в данный метод,
а теперь переменная number
тут, внутри имеет значение 100.
Запустим телефон.
Я ожидаю, что при нажатии кнопки
"Минус", number обновится до 100.
Так и есть.
Это лишь немногое, что вы можете
сделать, экспериментируя с
введением различных входных
величин в метод.
По мере работы с входными
параметрами,
вы встретите еще один термин -
arguments.
Когда вы вызываете метод,
входные величины, вводимые в такой
метод, называются аргументами.
Это немного смешное слово.
Когда думаешь об аргументах, в
голову приходят орущие и проклинающие
друг друга люди.
Но тут все совсем не так.
Аргументы - это просто входные
данные, вводимые в метод.
Входные параметры это действующие
входные данные вашего метода и
они являются переменными, которые
используютя в методе.
Так что есть легкое отличие между
входным параметром и аргументом.
В любом случае, почитайте статью и
инструкции о параметрах метода.
Затем поэкспериментируйте с
кодом в вашем приложении.
Сначала попробуйте переименовать
входной параметр number
в объявлении метода displayQuantity.
Просто дайте ему другое
название переменной.
Затем исправьте ошибки, если есть,
и снова запустите приложение.
В следующем тесте измените тип данных
входного параметра number с int
на что-то еще типа String.
Посмотрите, что произойдет и
отмените внесенные изменения.
Если хотите поэкспериментировать с
другими вещами, вперед!
Например, если у вас есть вопрос
что случится, если я сделаю Х,
действуйте и пробуйте.
Bekleyin.
>> Ne oldu?
>> Bu ne zaman bir anda yemek pişirme programına dönüştü?
>> Metodlardan konuşmak zorunda kaldığımızdan beri?
>> Açıklamak ister misiniz, Rachael Ray?
>> [GÜLÜŞ] Hiç daha önce bir pasta pişirdiniz mi?
>> Daha önce pasta yedim.
>> Tamam.
O zaman bunun için tam donanımlısın.
>> Tamam.
>> Bir pasta pişirmek için yapmanız gereken un koymak, şeker koymak.
>> İçindekiler.
Tamam.
>> İçindekiler.
Evet.
Sonra da tarifteki talimatları takip edersiniz.
>> Tamam.
>> Ve sonra da pasta meydana gelir.
>> Bunun gibi mi?
>> Evet.
>> Tamam. İyi
Bu benzetmeyi metodlarla bir daha bağlantılandırın.
>> Tamam. Kesinlikle
Bu metod için girdileri koyabilirsiniz.
>> Görüntüleme metodu için miktarı yaptığımız gibi mi?
>> Evet, ve sonra metoddaki talimatları yapıyorsunuz.
>> Tamam, aynı bir pasta tarifi gibi mi?
>> Mm-hm.
Sonra çıktı değerini dönüş olarak alabilirsiniz.
>> Çıktılar, onlar lezzetlidir.
>> [GÜLÜŞ]
>> Şimdi daha fazla bilgiye bakalım
Metodlar için girdi parametreleri hakkında.
Java metodu parametresi için bir Google araması yapacağım.
İlk link güzel görünüyor, ona tıklayacağım.
Şimdi bu makale bilgiyi bir metoda geçirmekten bahsediyor.
Bir ev kirası için aylık ödemeleri hesaplayan bir kod kırpıcı var.
Dört girdi parametresi var; kira miktarı, faiz oranı, kiranın gelecekteki
Değeri ve kira uzunluğunun dönem sayısı.
Ve sonra bu metodun içinde bu girdi parametrelerini
Kendi matematik hesaplamalarımızı yapmak için değişken olarak kullanabiliriz.
Ödemeyi hesapla metodunu çağırdığımızda
Girdileri bu spesifik düzende geçirmemiz gerekir.
Yani kira miktarı önce gitmeli, sonra oran ve böyle.
Bu kısımdaki test için,
Bu makaleyi detaylıca inceleme şansınız olacak.
Masa üstü Java uygulamasındaki ana aktivite içinde
Miktarı görüntüleme metodunu ve girdi parametresini
Düzenleyerek size biraz pratik sağlayacağız.
Uygulamamızın azaltma metodunda
Miktarı görüntğleme metodu dediğimiz,
Bu metoda girdi olarak miktar değişkenini geçiriyoruz.
Ama girdi parametresinin adı "rakam", yani
Biz ne zaman bu girdiye atıf yapmak istesek, sadece rakam dememiz yeterli.
Şimdi teknik olarak bu metodun içinde bir girdi parametresi olarak
Geçirmek yerine küresel miktar değişkenini kullanabilirdik.
Ama size girdi parametrelerini öğretmek amacıyla
Onu olduğu gibi bırakalım.
Bu miktar görüntüleme metoduna çağrıyı
Girdiyi geçecek şekilde, 30 rakamı olarak değiştirebilirim.
Bu geçerli çünkü hala girdi verisi türüne uyuyor.
Azaltma metodunda miktarı görüntülemeyi çağırdığımızda
Buraya zıplayacak ve bu talimatları yerine getirecek
Ve değişken numarası 30 olacak.
Size göstermek için kendi cihazımda çalıştıracağım, şimdi ne zaman eksi
Düğmesini uygulamamda kullansam, burada 30 miktarını gösterecek.
Haydi deneyeyim.
Burada. Ve gerçekten böyle oldu.
Farklı bir değişken de oluşturabilirim ve bunu metoda bir girdi olarak geçirebilirim.
Burada miktar olarak isimlendirilen bir yerel değişken oluşturdum
Ve onu 100 ile başlattım.
Bu değişken girdisini bu metoda geçirdim
Ve şimdi değişken içindeki rakamın değeri 100.
Bunu cihazda çalıştırayım.
Şimdi ne zaman eksiltme düğmesine bassam miktar 100'e güncellenecek.
Ve oluyor.
Bunlar sizin farklı girdileri bir metoda geçirerek
Deneyebileceğiniz bazı şeyler.
Siz girdi parametreleriyle çalışırken
Karşılaşabileceğiniz diğer bir kavram argümanlar.
Bir metodu çağırdığınızda
O metoda geçirilen girdilere argüman adı verilir.
Bu eğlenceli bir kelimedir.
Çünkü argüman kelimesini düşündüğünüzde, aklınıza
Birbirine bağırıp küfreden insanlar gelir.
Ama bu böyle değil.
Argümanlar bir metoda geçen girdilerdir.
Girdi parametreleri sizin metod deklarasyonunuzdaki gerçek girdilerdir ve
Metodunuz içinde kullanılan değişkenler bunlardır.
Girdi parametresi ile argümanlar arasındaki hafif bir farklılıktır.
Her durumda, metod parametreleri hakkında
Makale ve eğitmen notlarını okuyun.
Sonra kodu uygulamanızda deneyin.
Önce görüntüleme miktar metodu deklarasyonunda
Girdi parametresini yeniden isimlendirmeyi deneyin.
Sadece ona farklı bir değişken ismi verin.
Sonra hataları düzeltin ve uygulamayı tekrar çalıştırın.
Sonraki test için, gidin ve veri türünü değiştirin
Tam sayıdan Dizi gibi bir şeye girdi parametresinden.
Ne olduğunu izleyin ve sonra gidip değişikliği iptal edin.
Diğer şeylerle denemek istiyorsanız, deneyin.
Örneğin X'i yaparsam ne olur gibi sorularınız varsa
Sadece deneyin.
Chờ đã.
Sao vậy?
Tại sao tự nhiên lại biến thành
chương trình nấu ăn thế này?
Vì chúng ta phải nói về phương thức?
Cậu giải thích được không,
Rachael Ray?
[CƯỜI] Chà, thế cậu
đã bao giờ nướng bánh chưa?
Tôi từng ăn bánh rồi.
Ok.
Thế là cậu đủ tiêu chuẩn
làm việc này rồi.
Được rồi.
Tất cả những gì cậu cần làm để làm
một chiếc bánh là cho bột, đường.
- Các nguyên liệu.
- Nguyên liệu.
- Đúng.
- Phải rồi.
Và sau đó tuân theo
những chỉ dẫn trong công thức.
Ok.
Và thế là xong một cái bánh.
Như thế này hả?
Đúng rồi.
Ừ.
Chà, cậu có thể
liên hệ với phương thức
lần nữa được không?
Tất nhiên rồi.
Đương nhiên với
một phương thức,
bạn phải cho đầu vào.
Như chúng ta đã làm với khối lượng
cho phương thức hiển thị phải không?
Đúng, và rồi cậu thực hiện
theo chỉ dẫn của phương thức.
Ok, vậy giống như công thức làm bánh?
Ừ, sau đó cậu sẽ có
đầu ra trả lại.
Đầu ra ư, ngon phết nhỉ.
[CƯỜI]
Hãy cùng xem thêm thông tin
về tham số đầu vào
cho các phương thức.
Tôi sẽ tìm kiếm trên Google
với từ khóa tham số phương thức Java.
Kết quả đầu tiên có vẻ được
nên tôi sẽ bấm vào đó.
Bài viết này nói về việc
thêm thông tin vào trong phương thức.
Đây là một đoạn code nhỏ lập trình khỏan
thanh toán tiền vay mua nhà hàng tháng.
Nó có bốn tham số đầu vào,
tiền thuê, lãi suất, giá trị tương lai
của khoản vay, cũng như số lượng các kỳ
và kỳ hạn của khoản vay.
Và trong phương thức này, ta thấy
ta có thể sử dụng các tham số đầu vào
giống như các biến
trong toán học.
Khi ta gọi phương thức
tính khoản thanh toán,
chúng ta phải đảm bảo rằng mình
nhập vào đúng dữ liệu, theo đúng thứ tự.
Vì vậy giá trị khoản vay phải ở đâu tiên,
sau đó đến lãi suất và cứ thế.
Trong câu hỏi ở phần này,
bạn sẽ có cơ hội để kiểm chứng
bài viết này một cách kỹ càng hơn.
Trong mục thực thi chính của
ứng dụng Java,
chúng ta sẽ thay đổi phương thức
hiển thị khối lượng và
tham số đầu vào
để giúp các bạn thực hành.
Lưu ý rằng trong phương thức giảm
trong ứng dụng của chúng ta,
cái mà chúng ta gọi là
phương thức hiển thị khối lượng,
chúng ta đang sử dụng biến số lượng
làm đầu vào cho phương thức này.
Nhưng tham số đầu vào
được gọi là 'number', vì vậy
mỗi khi chúng ta muốn đề cập đến
đầu vào này, ta chỉ cần nói number.
Về mặt nguyên lý, ta có thể sử dụng
biến số lượng toàn cầu trong
phương thức này, thay vì
sử dụng nó như tham số đầu vào.
Nhưng để dạy các bạn về
tham số đầu vào,
hãy cứ làm như vậy.
Tôi có thể sửa phần triệu gọi này
thành phương thức hiển thị số lượng
vì vậy đầu vào của
chúng ta là số 30.
Điều này vẫn hợp lệ vì nó vẫn khớp
với định dạng dữ liệu đầu vào.
Do vậy trong phương thức giảm mà
chúng ta gọi là hiển thị số lượng,
nó sẽ nhảy xuống đây,
thực hiện theo chỉ dẫn, và
biến number sẽ có
giá trị bằng 30.
Tôi sẽ chạy thử trên thiết bị để bạn thấy
bây giờ nếu tôi chạy nút trừ
trên ứng dụng, nó sẽ
hiển thị giá trị 30 ở đây.
Để tôi thử xem.
Đây.
Và nó diễn ra đúng như thế.
Tôi cũng có thể tạo một biến khác và dùng
nó làm đầu vào cho phương thức này.
Ở đây tôi đã tạo một biến
nội bộ gọi là someQuantity và
tôi đặt nó bắt đầu từ 100.
Tôi dùng biến này
làm đầu vào cho phương thức,
và giờ thì biến number ở đây
đang có giá trị là 100.
Tôi sẽ chạy thử trên thiết bị.
Giờ tôi kỳ vọng khi bấm vào nút trừ,
số lượng sẽ được cập nhật thành 100.
Và đúng thế.
Đây chỉ là một vài thứ
mà bạn có thể thử
khi nhập những đầu vào
khác nhau vào một phương thức.
Khi làm việc với tham số đầu vào,
một thuật ngữ mà bạn
hay gặp là đối số.
Khi bạn gọi một phương thức,
những dữ liệu đầu vào được nhập vào
phương thức đó gọi là đối số.
Thuật ngữ này khá buồn cười.
Vì khi bạn nghe đối chọi,
bạn sẽ nghĩ tới việc la mắng
và nguyền rủa lẫn nhau.
Nhưng ở đây thì khác.
Đối số chỉ đơn giản là đầu vào
được nhập vào trong một phương thức.
Tham số đầu vào là những đầu vào
thực tế được xác định khi gọi phương thức.
Chúng là những biến được sử dụng
trong phương thức của bạn.
Như vậy, có chút khác biệt giữa tham số
đầu vào và đối số.
Dù sao, hãy tiếp tục
đọc bài viết và những
lưu ý của người hướng dẫn
về tham số đầu vào.
Sau đó tiếp tục thử nghiệm
code này trên ứng dụng.
Hãy bắt đầu bằng việc đổi tên
tham số đầu vào number,
bên trong phần xác định
phương thức hiển thị số lượng.
Đơn giản hãy tạo cho nó
một tên biến khác.
Cứ như thế, khắc phục lỗi
và chạy ứng dụng lần nữa.
Ở bài kiểm tra tiếp theo, hãy thử
thay đổi định dạng dữ liệu
của tham số đầu vào number từ số nguyên
thành thứ gì khác như chuỗi.
Hãy quan sát điều gì xảy ra và
quay lại như lúc đầu.
Nếu bạn vẫn thích thử nghiệm thêm
điều gì khác, cứ tự nhiên.
Ví dụ như, nếu bạn băn khoăn,
sẽ thế nào nếu mình làm x,
thì đừng ngại thử nó.
等等
怎么啦?
什么时候这个突然变成厨艺展示了?
因为我们必须讨论方法?
解释一下 Rachael Ray
好的 你曾经烤过蛋糕吗?
我之前吃过蛋糕
好的
好的 你完全有资格
好的
所有你烤蛋糕需要做的是放面 糖
那些佐料
是的 那些佐料
耶
之后你按照食谱
- 好的 - 就出来一个蛋糕
像这样?
是的
好的 很好
再次联系类比的方法
好的 所以为了
你能够给一个方法输入参数
比如我们在 display 方法放入 quantity
是的 之后你按照方法的指令执行
好的 就好像做蛋糕的食谱
嗯嗯
之后你可以返回输出值
输出 它们很美味
让我们搜索更多信息
关于方法的输入参数
我将要对 java method parameter 进行 Google 搜索
第一个链接看起来不错所以我要点击它
这篇文章谈论关于方法传递信息的知识
这有关于计算房屋按月贷款的预付款项的一段代码
它有四个输入参数 贷款额 利率
本息 和贷款的时间周期
之后我们可以用这个输入参数代替我们看到的方法
简单的如同变量去做数学计算
当我们调用计算computePayment方法
要确定我们按照这个特定顺序输入
所以付款额在第一位 之后是利率以及之后的
在这部分的测验
你将有机会更详细地回顾本文
在 the desk Java 应用的 Mainactivity 里
我们将要修改 display 方法和
练习输入参数的方法
注意我们的应用里的 decrement 方法
调用了 display quantity 方法
我们传入 quantity 变量给这个方法
不过这个输入参数叫 number 所以
无论何时我们想要引用这个输入 只需要声明 number
技术上讲在这个方法里我们使用全局变量
来代替传入一个参数
但是为了教授关于输入参数的知识
我们先这样
我能修改这个调用 displayQuantity 的方法
输入一个参数 30
这是有效的因为它是符合要求的数据类型
所以在 decrement 方法当我们调用 display quantity
它会跳到这里并执行这个指令
这个变量值将是30
我将在我的设备上给你演示 所以当我点击减号按钮
在我的应用 quantity 会显示30
让我试试这个
这里 就是我们预期的结果
我同样能创建不同变量并传递给这个方法
这里我创建一个局部变量叫 someQuantity 并且
将它初始化为100
将这个变量传给这个方法
现在变量的值就变为100了
让我在设备上运行
现在我希望当我点击减号按钮这个 quantity 更新为100
确实是这样
你可以试一下
不同的输入方法
当你使用输入参数
你可能会遇到其他的术语叫实参
当你调用方法时
传递给方法的参数叫实参
现在这是一种有趣的单词
因为当你听到 arguments 你将会想到人们争吵
咒骂别人
不过这不是这样的
实参就是简单地传递给方法的输入
形参就是方法定义时
声明需要的输入
形参和实参有一点区别
无论如何 看看笔记
关于方法参数的文章
之后在你的应用里体验一下他们的用法
首先试着重命名 number 形参
在 display quantity 方法声明里
只是给不同变量命名
之后修改错误 再次运行应用
在下一个练习 修改数据类型
将形参 number 从 int 型转变为 String 型
观察会发生什么并取消修改
如果你可以尝试其他的东西
例如 如果你有一个问题
如果我做X 会发生什么 然后继续并尝试它
稍等。
>> 怎么了?
>> 这怎么突然变成烹饪节目了?
>> 因为我们得解说方法不?
>> 能解释吗,Rachael Ray?
>> [笑声] 你有烘烤蛋糕的经验吗?
>> 我吃过蛋糕。
>> 好吧。
那你完全能胜任这一点。
>> 好。
>> 你只需放入面粉和糖。
>> 烘烤成分。
对。
>> 那些成分。
是的。
然后你照着食谱上的指示。
>> 是。
>> 然后蛋糕就完成了。
>> 就这样?
>> 是呀。
>> 好吧。
再把比喻和方法连接起来。
>> 好的,没问题。
在一个方法中,你可输入数据。
>> 就像我们在显示方法中做的数量?
>> 是的,接着你执行该指示。
>> 好,就好像烘培蛋糕的食谱?
>> 嗯。
然后你会有输出值回流。
>> 输出值,真美味。
>> [笑声]
>> 让我们来看看更多
关于输入方法参数的资料。
我打算到谷歌搜索Java方法的参数。
第一个链接看起来不错,我要点击一下。
这篇文章谈到传递信息的方法。
这里有个用于计算每月支付住房贷款的代码片断。
它有4个得输入的参数,贷款金额,利息率,未来贷款的收益
以及贷款期限。
通过这方法我们能够用这些
简单的参数作为我们算法的变量。
当我们调用贷款支付方法时,
我们得确保依据特定的顺序输入参数。
因此得先输入贷款金额,然后利息率等。
此部分的测验中,
你可以更详细的阅读这篇文章。
在Java应用程序的主要活动,
我们将以修改显示数量的方法和
输入的参数作为你的练习。
注意在应用程序中的减量法,
我们所称为显示参数的方法,
我们把数量变成方法的输入参数。
但这些参数被称为“号码”,
所以当我们要引用这参数,我们只需说出它的号码。
现今,我们可在这方法上使用
全球数量而不是将它变成方法的输入参数。
但为了教学目的,
就让它留着吧。
我可把这对话变成显示数量的方法
所以输入后,它变成30。
这是有效的,因为它仍是输入数据的类型。
于是在减量法时,我们把它称为显示的数量,
它会跳到这儿,然后执行这些指示,
然后这些变量将会变成30。
我向你展示在我的手机里的设置,当我在程序上
执行减量,它将在这显示数量为30。
让我尝试。
这。它真的是这样的。
我也可以创建一个不同的变量并将其作为一种输入的方法。
在这里,我创建了一个定量,接着
我把它的初期值设为100。
我把这这变量输入引用于该方法中,
现在该变量值100。
让我执行这例子。
现在我估计当我点击减号按钮时,该数量将更新为100。
确实是这样。
这都是一些你可以用来做实验的事情
通过方法不同的输入。
当你使用输入的参数,
你可能会遇到另个术语称为论据。
当你调用一个方法时,
输入的参数被传递的被称为论据。
这是有点有趣的词语。
因为arguments(争吵),你会想到大呼小叫
甚至互相咒骂着。
但并非如此。
Arguments (论据)是输入的参数被传为方法。
输入参数是方法声明中的实际的参数
这些是你使用的方法中的变数。
所以输入的参数和论据是略有区别的。
无论如何,你可以阅读该文章
这教员有记载关于方法的参数。
然后继续在你的应用程序中尝试这代码。
首先先尝试重命名输入数字的参数
于显示数量方法声明。
只需简单地给它一个不同的变量名称。
然后修复任何错误,再重新运行该应用程序。
在接下来的测试,试图改变输入数据的类型
像是从整数变成其他类型如 String。
观察结果然后撤消更改。
如果你想试验其他的,请便。
例如若你有一个问题,
如果我做X,会发生什么事?尽管去尝试。