Upload
yram-garciia
View
231
Download
0
Embed Size (px)
DESCRIPTION
Portafolios evidencias 2° Parcial Java
Citation preview
G
arc
ía C
ab
rera
Ma
. D
e J
esú
s
20
11
Po
rta
folio
s d
e E
vid
en
cia
s
Est
ruc
tura
de
Da
tos
II
En este documento tendrá acceso a un trabajo
de buena calidad, reflejo de cómo son impartidas
las clases en la UBAM, el programa se centra
especialmente en la materia de Estructuras de
Datos II para el Quinto Cuatrimestre de la carrera
de Ingeniería en Sistemas Computacionales.
Universidad Bancaria de México “Constancia, Unidad y Trabajo”
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
Estructura de Datos II ISC Edgar Jovani Salazar Sánchez
Evaluación (2° Parcial)
50% Examen
50% Proyecto
100%
*Portafolios derechoa examen
-4 practicas
-4 ensayos
-1 tarea
Reglas:
1.- 5 minutos de tolerancia (laboratorio no tolerancia)
2.- Prácticas (en tiempo y forma “individuales”)
3.- Proyectos dúos (en tiempo y forma)
4.- Portafolio Individual
No comida
No porno, juegos, celulares y consolas
La sanción es fuera una semana
Material necesario:
-NetBeans 9.6.1
-JDK 1.6
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
Sun compra MySql (Exposición)
Por la cantidad de 1000 millones de dólares, en 2008
*Desarrollo de BD en Google
Esto favoreció al OpenSource
La licencia de MySQL ya no es gratuita hoy en día
Se fusiona el software
MySQL es útil solamente para BD pequeñas
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
Ejemplo: Programa con captura desde teclando utilizando Scanner
import java.util.*;
import java.io.*;
public class lector
{
public static void main (String args[])
{
Scanner lector= new Scanner(System.in); //creando objeto
System.out.println("Dame tu nombre");
String nombre= lector.next();
System.out.println("Dame tu edad"); //lee en format string desde teclado
int edad= lector.nextInt();
System.out.println("Dame tu estatura");
double estatura= lector.nextDouble();
//no esta correcto el scanner, es por ello manda la excepcion en Main
//al momento de mostrar un tipo de dato double
System.out.println("Tu nombre es " + nombre + " tu edad es " + edad + " y tu
estatura es " + estatura);
}
}
NOTAS:
-Al contener un scanner lee todo tipo de datos a excepsion del doublé
-Para poder crear un método scanner es necesario utilizar la librería “UTIL.*”
-En caso de tener un Double se utiliza la siguiente línea:
System.out.println(“Dame estatura”);
Double estatura= lector.nextDouble();
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
Ejemplo: Programa para captura de teclado usando BufferedReader
import java.io.*;
public class lector2{
public static void main(String args[])
throws IOException{
BufferedReader Lec=new BufferedReader (new InputStreamReader
(System.in));
System.out.println("Dame tu nombre");
String nom=Lec.readLine();
System.out.println("Dame tu edad");
String age=Lec.readLine();
System.out.println("Dame tu estatura");
Lec.readLine();
String ed=Lec.readLine();
int edad=Integer.parseInt(ed);
}
}
NOTAS:
-No es necesaria la librería UTIL
-En el constructor se lee la cadena por teclado, el constructor del BufferedReder en
System se pasa tal cual esta
-El BufferedReader crea un canal de comunicación
-La ventaja del código anterior es que acepta el doublé
-Para poder llevar a cabo un cast
System.out.println(“Dame tu edad”);
Lec.ReadLine();
String ed= lec.ReadLine();
Int edad= Integer.parseInt(ed);
-La única ventaja es en un int y se ahorra mucho código
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
SENTENCIAS CONDICIONALES
1. if – else
2. switch
3. En línea
1.-if-else
If( )
{
}
else
{
}
2. en linea
String msg=(a>b)?
“mayor” : “b menor”;
3. Switch
Switch( )
{
Case 1:
Break;
}
Default: System.out.println(Opcion no valida”);
}
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
Ejercicio:
Distrito Municipio Folio Edad
Atizapan 1200 18 años
Distrito1 C. Izcalli 1201 18 años
San Mateo 1202 18 años
Coyotepec 1900 18 años
Distrito 2 Teoloyucan 1901 18 años
Huehuetoca 1902 18 años
Código:
import java.io.*;
import java.util.*;
public class menus{
public static void main (String args[])
{
Scanner lec= new Scanner (System.in);
System.out.println("Seleccione Distrito");
System.out.println("Distrito 1");
System.out.println("\t 1)Atizapan");//100
System.out.println("\t 2)Cuautitlan Izcalli");//200
System.out.println("\t 3)San Mateo");//300
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
System.out.println("");
System.out.println("Distrito 2");
System.out.println("\t 4)Coyotepec");//400
System.out.println("\t 5)Teoloyucan");//500
System.out.println("\t 6)Huehuetoca");//600
int distrito= lec.nextInt();
System.out.println("Digite municipio");
int municipio=lec.nextInt();
System.out.println("Ingrese numero de folio");
int folio = lec.nextInt();
System.out.println("Ingrese edad");
int edad=lec.nextInt();
switch(distrito)
{
case 1:
switch(municipio)
{
case 1:
switch(folio)
{
case 100:
break;
default: System.out.println("Verifique folio");
}
break;
case 2:
switch(folio)
{
case 200:
break;
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
default: System.out.println("Verifique folio");
}
break;
case 3:
switch(folio)
{
case 300:
break;
default: System.out.println("Verifique folio");
}
break;
default:System.out.println("Verifique municipio");
}
break;
case 2:
switch(municipio)
{
case 4:
switch(folio)
{
case 400:
break;
default: System.out.println("Verifique folio");
}
break;
case 5:
switch(folio)
{
case 500:
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
break;
default: System.out.println("Verifique folio");
}
break;
case 6:
switch(folio)
{
case 600:
break;
default: System.out.println("Verifique folio");
}
break;
default:System.out.println("Verifique municipio");
}
break;
default:System.out.println("verifique distrito");
}
if(edad>=18)
{
System.out.println("Usted puede votar");
}
else
{
System.out.println("Verifique edad");
}
}
}
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
CICLOS
1. FOR
For(i=0; i<=3; i++)
{
System.our.println(“Hola”);
}
2. WHILE
While( )
{
System.out.println(“Hola”);
}
3. DO
do {
system.our.println(“hola”);
}
while();
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
Ejercicio: Realizar un programa para checar hora de entrada y salida delos
empleados de una fábrica
-checador de trabajadores
*hora de entrada
*hora de salida
-El usuario debe digitar
*Nick o nombre de usuario
*hora de entrada en el formato hora:minutos
*La hora entrada y salida, se comparará con la hora del sistema
Código:
import java.io.*;
import java.util.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class horas
{
static String hora[]= new String[10];//horas digitadas por usuario
static String nombre[]= new String[10];//10 empleados
static String time[]= new String[10]; //10 horas obtenidas del sistema
public static void main(String arg[])
{
Scanner lector= new Scanner(System.in);
Calendar calen= new GregorianCalendar();
int e=0; //variable para for numeros de empleado
int w=1; //usar while
int num=0;
while(w==1)
{
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
System.out.println(".::Eliga una opcion del menu::.");
System.out.println("1. Trabajador");
System.out.println("2. Administrador");
System.out.println("3. Finalizar");
num=lector.nextInt();
if(num==1)
{
System.out.println(".::Ingrese sus datos::.");
System.out.println("Nombre de usuario:");
nombre[e]=lector.next();
System.out.println("La hora de entrada debera estar en el siguiente formato->
HH:MM");
System.out.println("Digite hora entrada");
hora[e]=lector.next();
String gethora=Integer.toString(calen.get(Calendar.HOUR));
String getmin=Integer.toString(calen.get(Calendar.MINUTE));
time[e]= gethora+":"+getmin; //mostrando hra real del sistema
e=e+1;//empleados
}
if(num==2)
{
System.out.println(".::Ingrese su nombre de usuario valor e"+e);
System.out.println("Usuario: ");
String user= lector.next();
System.out.println("Contraseña: ");
String pass= lector.next();
if(user.equals("yram") && pass.equals("war"))//Guardamos usuario y contraseña en un
arreglo
{
for (int e2=0; e2<e; e2++)
{
System.out.println("Empleado: " +nombre[e2]+ " hora real: "+ time[e2] + " hora
digitada por empleado: "+ hora[e2]);
}
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
}
else
{
System.out.println("Verifique sus datos");
}
}
}
if(num==3)
{
w=1;System.out.println("ha salido del sistema");
}
}
}
NOTAS:
*Para poder acceder a la hora del sistema por medio de java es necesario :
-usar librería import.java.util.*;
-crear una instancia
GregorianCalendar grc= new GregorianCalendar();
-Usar esta instancia para poder acceder a la vez a varias funciones especificas
de nuestra librería como por ejemplo:
° Era
° Year
° Month
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
ARREGLOS
Delararlo con un tamaño
Int arrgelos[];
int [] arreglos;
Int arreglos[]= new int[10]; // manejador de objeto creación de objetos
*¨*Arreglo representado gráficamente¨*¨
0 1 2 3 4 5 6 7 8 9
ASIGNACION DE VALORES
arreglos[0]=7;
int tamaño= arreglos.lenght(); //manipular el tamaño
arreglos.equals();
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
Ejercicio: Gato del tema arreglos y vectores
Código:
import java.io.*;
import java.util.*;
public class gato{
public static void main(String arg[]){
cat gat= new cat();
gat.all();
}
}
class cat
{
String Gato[][]=new String[3][3];
public void imprime()
{
System.out.println(Gato[0][0] + " | " + Gato[0][1] + " | " + Gato[0][2]);
System.out.println(Gato[1][0] + " | " + Gato[1][1] + " | " + Gato[1][2]);
System.out.println(Gato[2][0] + " | " + Gato[2][1] + " | " + Gato[2][2]);
}
public void all()
{
imprime();
Scanner lector= new Scanner(System.in);
Random rand = new Random();
int cx=0;
int cy=0;
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
System.out.println(".:Gato 1.0:.");
for(int r=0; r>cx; r++)
{
for(int c=0;c> cy; c++)
{
Gato[r][c]=" ";
}
}
int x = rand.nextInt(2);
if(x==0)
{
for(int t=0; t<9; t++)
{
System.out.println("Inicia: X");
do{
System.out.println("indica coordenadas x: ");
cx=lector.nextInt();
System.out.println("Digite coordenadas y: ");
cy=lector.nextInt();
while(cx>2 || cy>2);
Gato[cx][cy]="X";
imprime();
System.out.println("Inicia: O");
do{
System.out.println("indica coordenadas x: ");
cx=lector.nextInt();
System.out.println("Digite coordenadas y: ");
cy=lector.nextInt();
}
while(cx>2 || cy>2);
Gato[cx][cy]="O";
imprime();
}
}
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
}
else
{
for(int t=0; t<9; t++)
{
System.out.println("Inicia: O");
//System.out.println("random: "+x);
do{
System.out.println("indica coordenadas x: ");
cx=lector.nextInt();
System.out.println("Digite coordenadas y: ");
cy=lector.nextInt();
}
while(cx>2 || cy>2);
Gato[cx][cy]="O";
imprime();
System.out.println("Inicia: x");
//System.out.println("random: "+x);
do{
System.out.println("indica coordenadas x: ");
cx=lector.nextInt();
System.out.println("Digite coordenadas y: ");
cy=lector.nextInt();
}
while(cx>2 || cy>2);
Gato[cx][cy]="X";
imprime();
}
}
}
}
}
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
CLASS MATH
Es una clase base de java, a continuación se enlistan unas funciones que contiene:
1. Int max(int a, int b) : valor maximo
2. Double tan (double a) : tangente
3. Double exp (double a)
4. Double rin (double a) : tipo de redondeo, ejemplo double rin(0.8)
5. Int min (int , int b) : valor mas pequeño
6. Doublé asin (doublé a): arcsen
7. Log (double a) : logaritmo
8. Pow (double a) :potencia
Metodos Math
Math.floor (35.3) : valor por debajo de 35
Math.ceil (35.3) : valor alto = 36
Math.atan2(3.5) : en radianes
Math.abs (doublé x)
Math.acos : arccoseno
Math.sqrt (double x) : raiz cuadrada
Math.round (double x)
Math.sin (double x) : seno
Math.random(double x) : aleatorio
Math.cos (double x) : coseno
*el valor de “pi” y Euler son valores muy aproximados
*La class math viene por default
FUNCIONES BASICAS
int length(),
FUNCIONES DE COMPARACION
boolean equals (Object obj);
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
FUNCIONES VALUE OF
(Char boolean, int, log, float, doublé)
-static String ValueOf(tipo);
New Boolean (String).booleanValue();
Integer.parseint(String, int base);
Long.parseLong(String, int base);
new.Float(String).floatValue();
new.Double(String).doubleValue();
Ejemplo:
String a= “CADENA”;
if(a.equals(“CADENA”))
{
System.out.println(“Diferentes”);
}
if(a.equalsIgnoreCase(“CADENA”))
{
System.out.println(“iguales”);
}
VECTORES
*Declara un vector: Private Vector participantes=new Vector();
*No es necesario indicar el tamaño
*no se cierra
*Java.util.vector
*uso dinamico
*podemos usar cualquier tipo de dato y lo convierte en un objeto
*Add=agregar l final del vector
*FirstElement: primer elemento del vector pero al igual que las pilas en C el ultimo en
entrar es el primero en salir
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
*LastElement: ulrimo elemento del arreglo
System.out.println(“1 participante:” + participantes.FirstElement());
System.out.println(“ultimo participante:” + participantes.LastElement());
*IndexOf: Encuentra la posisicon del elemento
*Contains 5: indica si el lemento se encuentra
If(participantes.contains(“CHIVA”))
{
System.out.println(“chiva si se encuentra” + “su posición es” +
árticipantes.IndexOF);
*Remove: eliminar elemento del vector
Participantes.remove(“Angel”);
*Size: tamaño actual del vector
System.out.println(“Existen” + participantes.size());
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
MANIPULACION DE STRINGS
Ejercicio: Encriptar contraseña
String a= “HOLA”;
System.out.println(“La primera letra es: “ + a.charAt(0));
charAt(parámetro);
*De el parámetro que se le da al charAt obtenemos letra de acuerdo al numero que
se indique que es correspondiente también a la posición.
UNIVERSIDAD BANCARIA DE MEXICO “Constancia, Unidad y Trabajo”
U B A M
CONVERSIONES DE BINARIO, OCTAL Y HEXADECIMAL