1 / 12

método en Java

método en Java. definición. es un conjunto de instrucciones definidas dentro de una clase, que realizan una determinada tarea y a las que podemos invocar mediante un nombre. Algunos métodos que hemos utilizado hasta ahora: – Math.pow() – Math.sqrt () - System.out.println ();.

garry
Télécharger la présentation

método en Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. método en Java

  2. definición • es un conjunto de instrucciones definidas dentro de una clase, que realizan una determinada tarea y a las que podemos invocar mediante un nombre. • Algunos métodos que hemos utilizado hasta ahora: • – Math.pow() • – Math.sqrt() • - System.out.println();

  3. IMPLEMENTACIÓN DE MÉTODOS EN JAVA Pasos para implementar un método: 1.     Describir lo que el método debe hacer 2.     Determinar las entradas del método 3.     Determinar los tipos de las entradas 4.     Determinar el tipo del valor retornado 5.     Escribir las instrucciones que forman el cuerpo del método 6.     Prueba del método: diseñar distintos casos de prueba

  4. ESTRUCTURA GENERAL DE UN MÉTODO JAVA • La estructura general de un método Java es la siguiente: • [especificadores] tipoDevueltonombreMetodo([lista parámetros]) • { •     // instrucciones •    [return valor;] • }

  5. Métodos con parámetros. • Un método puede tener parámetros: • publicvo • Los parámetros los podemos imaginar como variables locales al método, pero su valor se inicializa con datos que llegan cuando lo • llamamos. id [nombre del método]([parámetros]) • { [algoritmo] }

  6. import java.util.*; • public class Metodos1 { •     public static void main(String[] args) { •         Scanner sc = new Scanner(System.in); • int numero1, numero2, resultado; • System.out.print("Introduce primer número: "); •         numero1 = sc.nextInt(); • System.out.print("Introduce segundonúmero: "); •         numero2 = sc.nextInt(); • resultado = sumar(numero1, numero2); • System.out.println("Suma: " + resultado); •     } •     public static intsumar(int a, int b){ • int c; •            c = a + b; •            return c; •     } • }

  7. Métodos que retornan un dato. • Un método puede retornar un dato: • public [tipo de dato] [nombre del método]([parámetros]) • { [algoritmo] • return [tipo de dato] } • Cuando un método retorna un dato en vez de indicar la palabra clave void previo al nombre del método indicamos el tipo de dato que retorna. Luego dentro del algoritmo en el momento que queremos que finalice el mismo y retorne el dato empleamos la palabra clave return con el valor respectivo.

  8. package bisiesto; • importjava.util.*; • publicclass Bisiesto { • publicstaticvoidmain(String[] args) { •         Scanner sc = new Scanner(System.in); • int año; • System.out.print("Introduce año: "); •         año = sc.nextInt(); • if(esBisiesto(año))  //llamada al método • System.out.println("Bisiesto"); • else • System.out.println("No es bisiesto"); • }/*** método que calcula si un año es o no bisiesto*/ • publicstaticbooleanesBisiesto(int a){    • if(a%4==0 && a%100!=0 || a%400==0) • return true; • else • return false;} }

  9. importjava.util.*; • publicclassMetodoVoid { • publicstaticvoidmain(String[] args) { •         Scanner sc = new Scanner(System.in); • String cadena; • System.out.print("Introduce cadena de texto: "); •         cadena = sc.nextLine(); • cajaTexto(cadena); //llamada al método • }/*** método que muestra un String rodeado por un borde*/ • publicstaticvoidcajaTexto(Stringstr){ • int n = str.length(); • for (int i = 0; i < n + 4; i++){ • System.out.print("#"); •             } • System.out.println(); • System.out.println("# " + str + " #"); • for (int i = 0; i < n + 4; i++){ • System.out.print("#"); •             } • System.out.println(); •     } • }

  10. importjava.util.Scanner; • publicclassMayorMenor { • publicvoidcargarValores() • { Scanner teclado=new Scanner(System.in); System.out.print("Ingrese primer valor:"); • int valor1=teclado.nextInt(); • System.out.print("Ingrese segundo valor:"); • int valor2=teclado.nextInt(); • System.out.print("Ingrese tercer valor:"); • int valor3=teclado.nextInt(); • intmayor,menor; • mayor=calcularMayor(valor1,valor2,valor3); menor=calcularMenor(valor1,valor2,valor3); System.out.println("El valor mayor de los tres es:"+mayor); System.out.println("El valor menor de los tres es:"+menor); }

  11. publicintcalcularMayor(int v1,int v2,int v3) • { int m; • if(v1>>v2 && v1>v3) • { m=v1; } • else { if(v2>v3) • { m=v2; } • else { m=v3; } } • return m; } • publicintcalcularMenor(int v1,int v2,int v3) • { int m; • if(v1<v2 && v1<v3) • { m=v1; } • else { if(v2<v3) • { m=v2; } else { m=v3; } } • return m; } • publicstaticvoidmain(String[] ar) • { MayorMenormaymen=new MayorMenor(); • maymen.cargarValores(); } }

More Related