Вы находитесь на странице: 1из 17

Elementos de Java

El objetivo de este laboratorio es presentar los elementos bsicos del lenguaje de programacin Java, tales como la declaracin y uso de variables y operadores.

Ejercicios de Laboratorio
Ejercicio Ejercicio Ejercicio Ejercicio Tarea 1: 2: 3: 4: Declarar, inicializar, imprimir variables Operadores condicionales Promedio de nmeros Hallando el mayor nmero

Ejercicio 1: Declarar, inicializar, imprimir variables


En este Ejercicio, se va a declarar e inicializar un a variable. Tambin se muestra cmo modificar y mostrar el valor de una variable. 1. Construir (Build) y ejecutar (Run) el programa Java OutputVariable utilizando NetBeans IDE 2. Construir (Build) y ejecutar (Run) el programa Java OutputVariable utilizando los comandos "javac" y "java"

(1.1) Construir (Build) y ejecutar (Run) el programa Java OutputVariable utilizando NetBeans IDE
0. Iniciar NetBeans IDE si no lo est. 1. Crear el proyecto

Seleccionar File en el men superior y seleccionar New Project. Observar que aparece la ventana de dilogo de New Project. Seleccionar Java en la seccin Categories y Java Application en la seccin Projects. Pulsar en Next.

En la seccin Name and Location, del campo Project Name, escribir MyOutputVariableProject. Este es el nombre que se le da al nuevo proyecto creado con NetBeans. En el campo Create Main Class, escribir OutputVariable. (Figura-1.10) Esto es para crear OutVariable.java, en el que el mtodo main(..) ser creado de forma automtica. Hacer Click en Finish.

Figura-1.10: Creacin del proyecto OutVariable

Observe que el nodo del proyecto MyOutputVariableProject se crea bajo el panel Projects del IDE NetBeans y que el fichero OutputVariable.java se muestra en la ventana del editor del IDE.

2. Modificar el fichero generado OutputVariable.java.

Modificar el OutputVariable.java como se muestra en Cdigo-1.11 y la Figura1.12 de abajo. Los fragmentos de cdigo que necesitan ser agregados esn resaltados en negrita y color azul.

/* * OutputVariable.java * * Created on January 19, 2010, 6:30 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ /** * * @author */ public class OutputVariable { /** * @param args the command line arguments

*/ public static void main(String[] args) { // Variable value is int primitive type and it is initialized to 10 int value = 10; // Variable x is char primitive type and it is initialized to 'A' char x; x = 'A'; // Variable grade is a double type double grade = 11; // Display the value of variable "value" on the standard output device System.out.println( value ); //Display the value of variable "x" on the standard output device System.out.println( "The value of x=" + x ); // Display the value of variable "grade" on the standard output device System.out.println( "The value of grade =" + grade ); } } Cdigo-1.11: Modificacin de OutputVariable.java

Figura-1.12: Modificacin de OutputVariable.java 3. Construir (Build) y ejecutar (run) el programa

Seleccionar con el botn derecho MyOutputVariableProject y seleccionar Run. Observar el resultado en la ventana Output del IDE NetBeans. (Figura-1.13)

Figura-1.13: Resultado de ejecutar el programa OutputVariable Volver al inicio del Ejercicio

(1.2) Construir (Build) y ejecutar (Run) el programa OutputVariable usando el compilador "javac" y "java"
1. Ir al directorio donde se va a escribir los programas Java C:\>cd \myjavaprograms 2. Escribir OutputVariable.java usando el editor de su preferencia (en este ejemplo se usa jedit) como se muestra en Cdigo-1.20.

C:\myjavaprograms>jedit OutputVariable.java public class OutputVariable { public static void main( String[] args ){ // Variable value is int primitive type and it is initialized to 10 int value = 10; // Variable x is char primitive type and it is initialized to 'A' char x; x = 'A'; // Display the value of variable "value" on the standard output device System.out.println( value ); // Display the value of variable "x" on the standard output device System.out.println( "The value of x=" + x ); } } Cdigo-1.20: OutputVariable.java 3. Compilar OutputVariable.java usando el compilador javac. El resultado de la compilacin es la creacin del fichero OutputVariable.class. C:\myjavaprograms>javac OutputVariable.java 4. Ejecutar el programa OutputVariable usando el comando java.El comando java inicia la Java Virtual Machine y ejecuta el programa OutputVariable en este ejemplo. Un programa Java puede estar compuesto de mltiples clases Java y un conjunto de libreras. En este ejemplo, el programa OutputVariable slo contiene una clase simple llamada OutputVariable.class. Se puede refereir al comando java como un intrprete de Java. C:\myjavaprograms>java OutputVariable 10 The value of x=A 7. Modificar OutputVariable.java como se muestra en Cdigo-1.21 abajo. La modificacin es para aadir la variable de tipo double llamada grade y mostrar el valor de la misma. Los fragmentos de cdigo que necesitan ser agregados esn resaltados en negrita y color azul. public class OutputVariable { public static void main( String[] args ){ // Variable value is int primitive type and it is initialized to 10 int value = 10; // Variable x is char primitive type and it is initialized to 'A' char x; x = 'A'; // Variable grade is a double type double grade = 11;

// Display the value of variable "value" on the standard output device System.out.println( value ); // Display the value of variable "x" on the standard output device System.out.println( "The value of x=" + x ); // Display the value of variable "grade" on the standard output device System.out.println( "The value of grade =" + grade ); } } Cdigo-1.21: Modificacin de OutputVariable.java 8. Compilar y ejecutar el programa. Observar el nuevo mensaje mostrado. C:\myjavaprograms>javac OutputVariable.java C:\myjavaprograms>java OutputVariable 10 The value of x=A The value of grade =11.0

Volver al inicio del ejercico

Resumen
En este ejercicio, se ha construdo y ejecutado el programa Java OutputVariable usando el compilador javac y el comando java y el IDE NetBeans. Volver al inicio

Ejercicio 2: Operador condicional


En este ejercicio, se va a escribir un programa Java que usa operadores condicionales. 1. Construir y ejecutar un programa Java que usa operadores condicionales

(2.1) Compilar y ejecutar un programa Java que usa operadores condicionales


1. Crear un proyecto NetBeans

Seleccionar File del men principal y seleccionar New Project. Observar que el dilogo New Project aparece. Seleccionar Java en la seccin Categories y Java Application en la seccin Projects. Click en Next. En el panel Name and Location, en el campo Project Name, escribir MyConditionalOperatorProject.

En el campo Create Main Class, ingresar ConditionalOperator. Click en Finish.

Observar que el nodo MyConditionalOperatorProject del proyecto es creado en el panel Projects del IDE NetBeans y que aparece ConditionalOperator.java en la ventana del editor del IDE.

2. Modificar el fichero ConditionalOperator.java generado.

Modificar ConditionalOperator.java como se muestra abajo en Cdigo-2.21. Los fragmentos de cdigo que necesitan ser agregados esn resaltados en negrita y color azul.

public class ConditionalOperator { /** * @param args the command line arguments */ public static void main(String[] args) { // Declare and initialize two variables, one String type variable // called status and the other int primitive type variable called // grade. String status = ""; int grade = 80;

// Get status of the student. status = (grade >= 60)?"Passed":"Fail"; // Print status. System.out.println( status ); } } Cdigo-2.21: Modificacin de ConditionalOperator.java 3. Construir (Build) y ejecutar (run) el programa

Seleccionar con el botn derecho MyConditionalOperatorProject y seleccionar Run. Observar el resultado en la ventana Output del IDE NetBeans. (Figura-2.22)

Figura-2.22: Resultado de ejecucin del programa

4. Modificar ConditionalOperator.java aadiendo las siguientes lneas de cdigo en el lugar apropiado, construir (Build) y ejecutar (run) el programa

int salary = 100000; Imprimir "You are rich!" si salary es mayor a 50000. Imprimir "You are poor!" en otro caso.

Resumen
En este ejercicio, se ha desarrollado una aplicacin Java usando el IDE NetBeans. Volver al inicio

Ejercicio 3: Promedio de nmeros


En este ejercicio, you are going to build and run a sample Java program in which an average of numbers are computed and displayed. 1. Construir y ejecutar un programa Java

(3.1) Construir y ejecutar un programa Java


1. Crear un proyecto NetBeans

Seleccionar File en el men superior y seleccionar New Project. Observar que el dilogo New Project aparece. Seleccionar Java en la seccin Categories y Java Application en la seccin Projects. Click Next. En el panel Name and Location, en el campo Project Name, escribir MyAverageNumberProject. En el campo Create Main Class, escribir AverageNumber. Click Finish.

Observar que se crea el nodo MyAverageNumberProject en el panel Projects del IDE NetBeans y que el IDE genera AverageNumber.java en la ventana del editor.

2. Modificar el cdigo generado AverageNumber.java.

Modificar AverageNumber.java como se muestra en Cdigo-3.11 abajo. Los fragmentos de cdigo que necesitan ser agregados esn resaltados en negrita y color azul.

public class AverageNumber { /** * @param args the command line arguments */ public static void main(String[] args) { //declares the three numbers int num1 = 10; int num2 = 20; int num3 = 45; //get the average of the three numbers // and saves it inside the ave variable int ave = (num1+num2+num3)/3; //prints the output on the screen System.out.println("number 1 = "+num1); System.out.println("number 2 = "+num2); System.out.println("number 3 = "+num3); System.out.println("Average is = "+ave);

} } Cdigo-3.11: Modificacin de AverageNumber.java 3. Construir (Build) y ejecutar (run) el programa

Seleccionar con el botn derecho MyAverageNumberProject y seleccionar Run. Observar el resultado en la ventana Output del IDE NetBeans. (Figura-3.12)

Figura-3.12: Resultado de ejecutar el programa AverageNumber

Volver al inicio

Ejercicio 4: Hallar el mayor nmero


En este ejercicio, se escribir un programa Java que usa operadores condicionales. 1. Construir y ejecutar un programa Java que usa operadores condicionales

(4.1) Construir y ejecutar un programa Java que usa operadores condicionales


1. Crear un proyecto NetBeans

Seleccionar File en el men principal y seleccionar New Project. Observar que aparece el dilogo New Project. Seleccionar Java en la seccin Categories y Java Application en la seccin Projects. Click Next. En el panel Name and Location, para el campo Project Name escribir MyGreatestValueProject. En el campo Create Main Class, escribir GreatestValue. (Figura-4.10) Click Finish.

Figura-4.10: Creacin de MyGreatestValueProject

Observar que el nodo del proyecto MyGreatestValueProject se crea en la seccin Projects del IDE de NetBeans y que se genera y muestra GreatestValue.java en la ventana del editor.

2. Modifcar el cdigo generado GreatestValue.java.

Modificar GreatestValue.java como se muestra en Cdigo-4.11. Los fragmentos de cdigo que necesitan ser agregados esn resaltados en negrita y color azul.

public class GreatestValue { /** * @param args the command line arguments */ public static void main(String[] args) { //declares the numbers int num1 = 10; int num2 = 23; int num3 = 5; int max = 0;

//determines the highest number max = (num1>num2)?num1:num2; max = (max>num3)?max:num3; //prints the output on the screen System.out.println("number 1 = "+num1); System.out.println("number 2 = "+num2); System.out.println("number 3 = "+num3); System.out.println("The highest number is = "+max); } } Cdigo-4.11: GreatestValue.java modificado 3. Construir (Build) y ejecutar (run) el programa

Seleccionar con el botn derecho MyGreatestValueProject y seleccionar Run. Observar el resultado en la ventana Output del IDE NetBeans. (Figura-4.12)

Figura-4.12: Resultado de ejecucin de MyGreatestValueProject

Volver al inicio

Tarea
1. La tarea es modificar el proyecto MyGreatestValueProject anterior. Se puede nombrar de cualquier manera al proyecto, pero aqu se le llama MyGreatestValueProject2.

Calcular el menor nmero y mostrarlo Si el menor nmero es menor que 10, mostrar el mensaje: "El menor nmero es menor que 10!". En otro caso, mostrar "El menor nmero es mayor o igual a 10!".

Вам также может понравиться

  • Ejercicio Segunda Parte
    Ejercicio Segunda Parte
    Документ8 страниц
    Ejercicio Segunda Parte
    Senin Ramon
    Оценок пока нет
  • Sesion 03
    Sesion 03
    Документ11 страниц
    Sesion 03
    Senin Ramon
    Оценок пока нет
  • Atención Al Cliente - Sesión 03
    Atención Al Cliente - Sesión 03
    Документ29 страниц
    Atención Al Cliente - Sesión 03
    Senin Ramon
    Оценок пока нет
  • Directorio Telef. Satelital Coes MTC 2023
    Directorio Telef. Satelital Coes MTC 2023
    Документ2 страницы
    Directorio Telef. Satelital Coes MTC 2023
    Senin Ramon
    Оценок пока нет
  • If 0702
    If 0702
    Документ4 страницы
    If 0702
    Senin Ramon
    Оценок пока нет
  • Link Emergencia y Explicacion de Uso de PVN
    Link Emergencia y Explicacion de Uso de PVN
    Документ2 страницы
    Link Emergencia y Explicacion de Uso de PVN
    Senin Ramon
    Оценок пока нет
  • Lo Que Debemos Distinguir Muy Claramente
    Lo Que Debemos Distinguir Muy Claramente
    Документ4 страницы
    Lo Que Debemos Distinguir Muy Claramente
    Senin Ramon
    Оценок пока нет
  • CV Pres
    CV Pres
    Документ1 страница
    CV Pres
    Technolgy_Personal
    Оценок пока нет
  • Ds - 011 2004 MTC
    Ds - 011 2004 MTC
    Документ2 страницы
    Ds - 011 2004 MTC
    Senin Ramon
    Оценок пока нет
  • Programación Gráfica Con Swing
    Programación Gráfica Con Swing
    Документ113 страниц
    Programación Gráfica Con Swing
    dny09
    Оценок пока нет
  • Instalacion de Tomcat y Configuracion de Eclipse PDF
    Instalacion de Tomcat y Configuracion de Eclipse PDF
    Документ3 страницы
    Instalacion de Tomcat y Configuracion de Eclipse PDF
    slopez05
    Оценок пока нет
  • Material Apoyo WebLogic
    Material Apoyo WebLogic
    Документ57 страниц
    Material Apoyo WebLogic
    Gabriel Briceño
    Оценок пока нет
  • 14.sesión Java - GUI
    14.sesión Java - GUI
    Документ22 страницы
    14.sesión Java - GUI
    mrnovoa
    Оценок пока нет
  • Liferay Portal HOWTO
    Liferay Portal HOWTO
    Документ8 страниц
    Liferay Portal HOWTO
    Patricio Ghirardi
    Оценок пока нет
  • Gui
    Gui
    Документ19 страниц
    Gui
    StevenPalacios
    Оценок пока нет
  • Ejb
    Ejb
    Документ40 страниц
    Ejb
    liker
    Оценок пока нет
  • Practica 3 Servlets
    Practica 3 Servlets
    Документ20 страниц
    Practica 3 Servlets
    eduard558
    Оценок пока нет
  • Resumen Spring v1
    Resumen Spring v1
    Документ12 страниц
    Resumen Spring v1
    Axl P
    Оценок пока нет
  • Facturas en Java
    Facturas en Java
    Документ17 страниц
    Facturas en Java
    Lenny Rally Conor
    Оценок пока нет
  • CV Eriksson Miguel Tapia Solis - Español
    CV Eriksson Miguel Tapia Solis - Español
    Документ3 страницы
    CV Eriksson Miguel Tapia Solis - Español
    Jorge Bazan Medina
    Оценок пока нет
  • Tomcat
    Tomcat
    Документ35 страниц
    Tomcat
    Xiomy Ch Ramos
    Оценок пока нет
  • Ensayo J2ee Subir
    Ensayo J2ee Subir
    Документ7 страниц
    Ensayo J2ee Subir
    Fanny Santos Cruz
    Оценок пока нет
  • Aplicación de Stock Con Java. Hibernate - MySQL - JPA.
    Aplicación de Stock Con Java. Hibernate - MySQL - JPA.
    Документ14 страниц
    Aplicación de Stock Con Java. Hibernate - MySQL - JPA.
    Diego Garcia
    Оценок пока нет
  • Proyecto Final Fase 1
    Proyecto Final Fase 1
    Документ30 страниц
    Proyecto Final Fase 1
    Neruda Baco
    Оценок пока нет
  • 42 Tomcat
    42 Tomcat
    Документ10 страниц
    42 Tomcat
    Miguel Chamorro Ramirez
    Оценок пока нет
  • Tema 2 - Servidores de Aplicaciones
    Tema 2 - Servidores de Aplicaciones
    Документ58 страниц
    Tema 2 - Servidores de Aplicaciones
    Mauricio Gonzalez
    Оценок пока нет
  • Base de Datos Sqlite
    Base de Datos Sqlite
    Документ4 страницы
    Base de Datos Sqlite
    Mariluz Mendoza
    50% (2)
  • Programacion4 - Parcial#2 JSF
    Programacion4 - Parcial#2 JSF
    Документ13 страниц
    Programacion4 - Parcial#2 JSF
    Jhesus Franco
    Оценок пока нет
  • Reloj Java
    Reloj Java
    Документ15 страниц
    Reloj Java
    Marvin Jacobo Bamaca Zacarias
    Оценок пока нет
  • Practica5 en Java Hilos
    Practica5 en Java Hilos
    Документ3 страницы
    Practica5 en Java Hilos
    carlos15ss
    Оценок пока нет
  • Profesor Java
    Profesor Java
    Документ37 страниц
    Profesor Java
    Rudy Franklin Condori Quilla
    Оценок пока нет
  • Introduccion Spring
    Introduccion Spring
    Документ47 страниц
    Introduccion Spring
    irving alejandro leonel amaral flores
    Оценок пока нет
  • Manual Netbeans
    Manual Netbeans
    Документ3 страницы
    Manual Netbeans
    Jhanin Reyes
    Оценок пока нет
  • Sesion 04 U II Poo II Gui 2
    Sesion 04 U II Poo II Gui 2
    Документ25 страниц
    Sesion 04 U II Poo II Gui 2
    Yoner Mendocilla
    Оценок пока нет
  • Ecodeup Compatrones de Diseno en Java MVC Dao y Dto
    Ecodeup Compatrones de Diseno en Java MVC Dao y Dto
    Документ11 страниц
    Ecodeup Compatrones de Diseno en Java MVC Dao y Dto
    Ivan Tqpt
    Оценок пока нет
  • Gradle Es
    Gradle Es
    Документ49 страниц
    Gradle Es
    Pepe Barron
    Оценок пока нет
  • M370 Ud03 V001
    M370 Ud03 V001
    Документ86 страниц
    M370 Ud03 V001
    joseant44
    Оценок пока нет
  • Jpa 05
    Jpa 05
    Документ23 страницы
    Jpa 05
    diego
    Оценок пока нет
  • Cursos CampusJoeDayz v1.0
    Cursos CampusJoeDayz v1.0
    Документ22 страницы
    Cursos CampusJoeDayz v1.0
    orionUPC
    Оценок пока нет