miércoles, 24 de junio de 2009

PRUEBA FINAL


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package prueba;

/**
*
* @author program
*/
import javax.swing.JApplet;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JOptionPane;

public class Main extends JApplet {
private int temp;

/**
* Initialization method that will be called after the applet is loaded
* into the browser.
*/
public void init() {
// TODO start asynchronous download of heavy resources
}

public void paint(Graphics g){
String aux=JOptionPane.showInputDialog(null,"VALOR DEL RADIO","RADIO",JOptionPane.PLAIN_MESSAGE);
double radio= Double.parseDouble(aux);
String aux2=JOptionPane.showInputDialog(null,"VALOR DEL ANGULO","ANGULO",JOptionPane.DEFAULT_OPTION);
double alpha=Double.parseDouble(aux2);
g.setColor(Color.blue);
g.drawOval(100, 100, 50, 50);
g.setColor(Color.red);
g.drawOval((int) (60), (int) (50), (int) radio, (int)radio);

double angulo;
String aux3=JOptionPane.showInputDialog(null,"VALOR EN X DE V","VELX",JOptionPane.PLAIN_MESSAGE);
double velx= Double.parseDouble(aux3);
String aux4=JOptionPane.showInputDialog(null,"VALOR EN Y DE V","VELY",JOptionPane.DEFAULT_OPTION);
double vely=Double.parseDouble(aux4);
String aux5=JOptionPane.showInputDialog(null,"VALOR EN X DE ACEL","ACX",JOptionPane.PLAIN_MESSAGE);
double acx= Double.parseDouble(aux5);
String aux6=JOptionPane.showInputDialog(null,"VALOR EN Y DE ACEL","ACY",JOptionPane.DEFAULT_OPTION);
double acy=Double.parseDouble(aux6);
String aux7=JOptionPane.showInputDialog(null,"VALOR DEL TIEMPO","T",JOptionPane.PLAIN_MESSAGE);
double t= Double.parseDouble(aux7);

double vo= Math.sqrt((velx*velx)+(vely*vely));
double w= (alpha/t);
double ac_ang= (w/t);
double vf= ((radio*w) + vo);
double y= radio*Math.sin((180-alpha)*Math.PI/180);
double x= radio*Math.sin((180-alpha)*Math.PI/180);

g.drawOval((int) (60), (int) (50), (int) radio, (int)radio);

double porc = (double)(temp*36)/10;
g.setColor(Color.white);
g.fillArc(50, 70, 100, 100, 0, (int)(porc));
g.setColor(Color.black);
g.drawString("La Wo es ", 180,60);
g.drawString("La VEL. en X es ", 180,80);
g.drawString("La VEL. en Y ", 180,100);
g.drawString("La ACEL. en X ", 180,120);
g.drawString("La ACEL. en Y es ", 180,140);
g.drawString("El TIEMPO es ", 180,160);
g.drawString("La ACEL. ANG. es ", 180,180);
g.drawString("La W es ", 180, 200);
g.drawString("La VEL. FINAL es ", 180,220);

g.setColor(Color.BLACK);
g.drawString(""+0, 320,60);
g.drawString(""+velx, 320,80);
g.drawString(""+vely, 320,100);
g.drawString(""+acx, 320,120);
g.drawString(""+acy, 320,140);
g.drawString(""+t, 320,160);
g.drawString(""+ac_ang, 320,180);
g.drawString(""+w, 320,200);
g.drawString(""+vf, 320,220);
}
}

lunes, 8 de junio de 2009

DINAMICA


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author Administrador
*/
import javax.swing.JApplet;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JOptionPane;

/**
*
* @author program
*/
public class Dinamica extends JApplet {

/**
* Initialization method that will be called after the applet is loaded
* into the browser.
*/
public void init() {
// TODO start asynchronous download of heavy resources
}

public void paint(Graphics g){
String aux=JOptionPane.showInputDialog(null,"VALOR DE LA BASE","BASE",JOptionPane.PLAIN_MESSAGE);
double x= Double.parseDouble(aux);
g.drawLine(30,150,(int)x+30,150 );
String aux2=JOptionPane.showInputDialog(null,"VALOR DE LA ALTURA","ALTURA",JOptionPane.DEFAULT_OPTION);
double y =Double.parseDouble(aux2);
g.drawLine((int)x+30, 150,(int)x+30,150-(int)y);
g.drawLine(30, 150, (int)x+30, 150-(int)y);

double angulo;
double tan=y/x;
angulo=Math.atan(tan);
angulo=Math.toDegrees(angulo);

String aux8=JOptionPane.showInputDialog(null,"DISTANCIA DE INICIO","DISTANCIA",JOptionPane.DEFAULT_OPTION);
double ab=Double.parseDouble(aux8);
double c=ab*Math.cos(angulo*Math.PI/180);
double xo=30+c;
double l=ab*Math.sin(angulo*Math.PI/180);
double yo=150-l;
double d=20*Math.cos(angulo*Math.PI/180);
double xo1=xo+d;
double m=(c+d)*Math.tan(angulo*Math.PI/180);
double yo1=150-m;
g.setColor(Color.darkGray);
g.drawLine((int)xo,(int)yo,(int)xo1,(int)yo1);
double dx=10*Math.sin(angulo*Math.PI/180);
double dy=10*Math.cos(angulo*Math.PI/180);
double xo2=xo1-dx;
double yo2=yo1-dy;
g.drawLine((int)xo1,(int)yo1,(int)xo2,(int)yo2);
g.drawLine((int)xo2,(int)yo2,(int)(xo-dx),(int)(yo-dy));
g.drawLine((int)(xo-dx),(int)(yo-dy),(int)xo,(int)yo);

String aux3=JOptionPane.showInputDialog(null,"VALOR DE LA FUERZA","FUERZA",JOptionPane.DEFAULT_OPTION);
double fuerza=Double.parseDouble(aux3);
String aux4=JOptionPane.showInputDialog(null,"VALOR DE LA MASA","MASA",JOptionPane.DEFAULT_OPTION);
double masa=Double.parseDouble(aux4);
String aux5=JOptionPane.showInputDialog(null,"VALOR DEL COEFICIENTE DE ROZAMIENTO","COEFICIENTE DE ROZAMIENTO",JOptionPane.DEFAULT_OPTION);
double miu=Double.parseDouble(aux5);
String aux6=JOptionPane.showInputDialog(null,"VALOR DEL TIEMPO","TIEMPO",JOptionPane.DEFAULT_OPTION);
double tiempo=Double.parseDouble(aux6);

double gravedad=9.8;
double aceleracion;
aceleracion=(fuerza/masa)-(gravedad*((miu*Math.cos(angulo*Math.PI/180))+Math.sin(angulo*Math.PI/180)));
double desplazamiento= aceleracion*0.5*tiempo*tiempo;
double xn=desplazamiento*Math.cos(angulo*Math.PI/180);
double yn=desplazamiento*Math.sin(angulo*Math.PI/180);
g.setColor(Color.BLUE);
g.drawLine((int)(xo+xn),(int)(yo-yn), (int)(xo1+xn), (int)(yo1-yn));
g.drawLine((int)(xo1+xn),(int)(yo1-yn),(int)(xo2+xn),(int)(yo2-yn) );
g.drawLine((int)(xo2+xn),(int)(yo2-yn),(int)(xo+xn-dx),(int)(yo-yn-dy) );
g.drawLine((int)(xo+xn-dx),(int)(yo-yn-dy),(int)(xo+xn),(int)(yo-yn) );


g.setColor(Color.MAGENTA);
double yb=5*Math.sin((angulo)*Math.PI/180);
double xb=5*Math.cos((angulo)*Math.PI/180);
double frx=0.1*miu*masa*gravedad*Math.cos(angulo*Math.PI/180);
double fry=0.1*miu*masa*gravedad*Math.sin(angulo*Math.PI/180);
g.drawLine((int)(xo+xn-xb+(0.5*d)),(int)(yo-yn-yb-dx),(int)(xo+xn-xb+(0.5*d)-frx),(int)(yo-yn-yb-dx+fry) );
g.drawString("µ",(int)(xo+xn-xb+(0.5*d)-frx-15),(int)(yo-yn-yb-dx+fry));

g.setColor(Color.ORANGE);
double ny=0.1*masa*gravedad*Math.cos(angulo*Math.PI/180);
double nx=0.1*masa*gravedad*Math.sin(angulo*Math.PI/180);
g.drawLine((int)(xo+xn-xb+(0.5*d)),(int)(yo-yn-yb-dx),(int)(xo+xn-xb+(0.5*d)-nx),(int)(yo-yn-yb-dx-ny));
g.drawString("N",(int)(xo+xn-xb+(0.5*d)-nx-20),(int)(yo-yn-yb-dx-ny));
g.setColor(Color.PINK);
double fx=0.1*fuerza*Math.cos(angulo*Math.PI/180);
double fy=0.1*fuerza*Math.sin(angulo*Math.PI/180);
g.drawLine((int)(xo+xn-xb+(0.5*d)),(int)(yo-yn-yb-dx),(int)(xo+xn-xb+(0.5*d)+fx),(int)(yo-yn-yb-dx-fy) );
g.drawString("F",(int)(xo+xn-xb+(0.5*d)+fx-15),(int)(yo-yn-yb-dx-fy));

g.setColor(Color.GREEN);
double peso=0.1*masa*gravedad;
g.drawLine((int)(xo+xn-xb+(0.5*d)),(int)(yo-yn-yb-dx),(int)(xo+xn-xb+(0.5*d)),(int)(yo-yn-yb-dx+peso) );
g.drawString("P",(int)(xo+xn-xb+(0.5*d)-15),(int)(yo-yn-yb-dx+peso));

g.setColor(Color.BLUE);
g.drawString("La FUERZA es ", 180,60);
g.drawString("La MASA es ", 180,80);
g.drawString("El TIEMPO es ", 180,100);
g.drawString("El ROZAMIENTO es ", 180,120);
g.drawString("La ACELERACION es ", 180,140);
g.drawString("El DESPLAZAMIENTO es ", 180,160);

g.setColor(Color.BLACK);
g.drawString(""+fuerza, 320,60);
g.drawString(""+(short)masa, 320,80);
g.drawString(""+tiempo, 320,100);
g.drawString(""+miu, 320,120);
g.drawString(""+(short)aceleracion, 320,140);
g.drawString(""+(short)desplazamiento, 320,160);
}
}

d

domingo, 7 de junio de 2009

TERMOMETRO




















package temperatura;

import java.awt.Color;
import java.awt.Graphics;
import java.applet.Applet;
import javax.swing.JApplet;
import javax.swing.JOptionPane;
import javax.swing.JOptionPane;

/**
*
* @author Administrador
*/
public class NewJApplet extends Applet {
public void init(){

}
public void paint(Graphics g){

g.drawRect(200, 50, 20, 100);
g.drawOval(50, 70, 100, 100);
g.drawString("-10ºC", 230, 150);
g.drawString("+100ºC", 230, 50);
g.drawString("50ºC", 20, 120);
g.drawString("75ºC", 90, 180);
g.drawString("100ºC", 150, 120);
String aux = JOptionPane.showInputDialog(null,"Ingrese la temperatura deseada","titulo",JOptionPane.DEFAULT_OPTION);

int temp = Integer.parseInt(aux);

double porc = (double)(temp*36)/10;
g.setColor(Color.MAGENTA);
g.fillArc(50, 70, 100, 100, 0, (int)(porc));

g.drawString("+"+temp+"ºC", 230, 150-temp);
g.setColor(Color.BLUE);
if (temp >80){
g.setColor(Color.RED);
g.fillOval(10, 10, 50, 50);
g.fillRect(200, 50, 20, 100-temp);
g.drawString("Alerta", 30, 10);


}

g.fillRect(200, 50, 20, 100-temp);
}
}

miércoles, 3 de junio de 2009

import java.awt.*;
import javax.swing.*;
import javax.swing.JOptionPane;
public class DemoPanel extends JFrame{
Container contenedor;

private JPanel panelMatriz;
private JTextField[][]blancos;
private int numeroColumnas;
private int numeroFilas;


public DemoPanel(){
super("BIENVENIDO AL SISTEMA");

String aux1="PROGRAMA DE OPERACIONES CON MATRICES\n";
aux1+="ESCOJA LA OPCION DESEADA:\n1.-SUMAR\n2.-RESTAR\n3.-MULTIPLICAR\n";
String aux=JOptionPane.showInputDialog(null,aux1,JOptionPane.DEFAULT_OPTION);
double d= Double.parseDouble(aux);
if (d==1){
String aux9="SUMAR";
JOptionPane.showMessageDialog(null,(d)+aux9,"OPCION ESCOGIDA",JOptionPane.DEFAULT_OPTION);}
if(d==2){
String aux9="RESTAR";
JOptionPane.showMessageDialog(null,(d)+aux9,"opcion escogida",JOptionPane.DEFAULT_OPTION);}
if(d==3){
String aux9="MULTIPLICAR";
JOptionPane.showMessageDialog(null,(d)+aux9,"opcion escogida",JOptionPane.DEFAULT_OPTION);}

String aux2="INGRESE";

aux2+="NUMERO DE FILAS: \n";
String aux3=JOptionPane.showInputDialog(null,aux2,JOptionPane.DEFAULT_OPTION);
double m= Double.parseDouble(aux3);
JOptionPane.showMessageDialog(null,""+(m),"NUMERO DE FILAS",JOptionPane.DEFAULT_OPTION);
String aux4="INGRESE";
aux4+="NUMERO DE COLUMNAS.\n";
String aux5=JOptionPane.showInputDialog(null,aux4,JOptionPane.DEFAULT_OPTION);
double n= Double.parseDouble(aux5);
JOptionPane.showMessageDialog(null,""+(n),"NUMERO DE COLUMNAS",JOptionPane.DEFAULT_OPTION);

numeroFilas=(int)m;
numeroColumnas=(int)n;
contenedor= getContentPane();
blancos=new JTextField[numeroFilas][numeroColumnas];
panelMatriz=new JPanel(new GridLayout(numeroFilas,numeroColumnas,5,5));
for(int i=0;i for(int j=0;j blancos[i][j]=new JTextField("blanco"+i+" "+j);
panelMatriz.add(blancos[i][j]);
}
contenedor.add(panelMatriz, BorderLayout.NORTH);
setSize(800,600);
setVisible(true);
}
}

public static void main(String args[]){
DemoPanel aplicacion=new DemoPanel();
aplicacion.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}

miércoles, 27 de mayo de 2009

PANELES


import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class DemoPanel extends JFrame {
Container contenedor;
private JPanel panelinicio;
private JPanel panelfin;
private JButton [][] botones;
private JLabel [][] texto;
private JPanel panelcampo;
private JPanel panelcampo1;
private JTextField[][] campo;
private JTextField[][] campo1;

public DemoPanel(){
botones= new JButton[2][2];
contenedor= getContentPane();
panelinicio= new JPanel(new GridLayout(2,2));
String [] nombres = {"enero","febrero","marzo","abril"};

int k=0;
for(int i=0; i<2; i++){
for(int j=0; j<2; j++){
//for(int i=0; i //for(int j=0; j<3; j++){
//botones[i][j]= new JButton("boton"+i+" "+j);
botones[i][j]= new JButton(nombres [k]);
k +=1;
panelinicio.add(botones[i][j]);
}
}
contenedor.add(panelinicio,BorderLayout.NORTH);
setSize(425,150);
setVisible(true);
texto= new JLabel[5][5];
panelfin= new JPanel(new GridLayout(5,5,10,10));
for(int i=0; i<5; i++){
for(int j=0; j<5; j++){
texto[i][j]= new JLabel("texto"+i+" "+j);
panelfin.add(texto[i][j]);


}
contenedor.add(panelfin,BorderLayout.SOUTH);
}
campo= new JTextField[4][3];
panelcampo= new JPanel(new GridLayout(4,3,5,5));
for(int i=0; i<4; i++){
for(int j=0; j<3; j++){
campo[i][j]= new JTextField("campo"+i+" "+j);
panelcampo.add(campo[i][j]);

}
contenedor.add(panelcampo,BorderLayout.WEST);
}
campo1= new JTextField[2][4];
panelcampo1= new JPanel(new GridLayout(4,2,5,5));
for(int i=0; i<2; i++){
for(int j=0; j<4; j++){
campo1[i][j]= new JTextField("campo1"+i+" "+j);
panelcampo1.add(campo1[i][j]);

}
contenedor.add(panelcampo1,BorderLayout.EAST);
}
}

public static void main(String args[]){
DemoPanel aplicacion= new DemoPanel();
aplicacion.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}

lunes, 25 de mayo de 2009

SENOIDAL, COSENOIDAL, Y RECTA


import java.applet.Applet;
import java.awt.*;
public class Varias extends Applet {
public void paint(Graphics g){
double m=1;
int a=1;
int b=1;
g.drawString("f(x)", 250, 475);
g.drawString("f (seno)", 410, 260);
g.drawString("f(coseno)", 410, 170);
g.drawString("Ec.de la recta", 120, 100);
g.drawLine(40, 40, 40, 450);
g.drawLine(20, 270, 450, 270);
g.setColor(Color.ORANGE);

for(int i=0;i<360; i=i+2)
{
int l=a*i+b;

int k=(int) (265 - 100*(Math.sin(l*3.1416/180)));
k= k*(int)m;
int n=(int) (265 - 100*(Math.cos(l*3.1416/180)));
int o=a*i+b;

g.fillOval( 38 + i,k,6,6);
g.fillOval( 38 + i,n,6,6);
g.fillOval( a*(38 + i)+b,(int) 265-(a*i)+b,6,6);
}


g.setColor(Color.black);
g.drawLine(40, 165, 398, 165);
g.drawLine(40, 370, 398, 370);
g.drawLine(131, 165, 131, 370);
g.drawLine(221, 165, 221, 370);
g.drawLine(311, 165, 311, 370);
g.drawLine(401, 165, 401, 370);
g.setColor(Color.BLACK);
g.drawString("-1", 30, 370);
g.drawString("0", 30, 270);
g.drawString("1", 30, 165);
g.drawString("¶/2", 115, 280);
g.drawString("¶", 205, 280);
g.drawString("3¶/2", 285, 280);
g.drawString("2¶", 405, 280);
g.drawLine(40, 40, 35, 55);
g.drawLine(35, 55, 45, 55);
g.drawLine(45, 55, 40, 40);
g.drawLine(450, 270, 425, 265);
g.drawLine(425, 265, 425, 275);
g.drawLine(425, 275, 450, 270);
g.setColor(Color.BLUE);
g.drawString("x", 460, 270);
g.drawString("Y-f(x)", 25, 35);
int ymax=this.getHeight();
int xmax=this.getWidth();
this.setSize(600, 500);
}
}

SENOIDAL


import java.applet.Applet;
import java.awt.*;
public class Seno extends Applet {
public void paint(Graphics g){
g.drawString("f(x)=Sen(x)",225, 75);
g.drawLine(40, 40, 40, 450);
g.drawLine(35, 270, 450, 270);
g.setColor(Color.MAGENTA);
for(int i=0; i<360; i=i+2)
{
g.fillOval( 38 + i,(int) (265 - 100*(Math.sin(i*3.1416/180))),8, 5);
}
g.setColor(Color.BLACK);
g.drawLine(40,165, 398, 165);
g.drawLine(40,370,398,370);
g.drawLine(131,165, 131, 370);
g.drawLine(221,165,221,370);
g.drawLine(311,165, 311, 370);
g.drawLine(401,165,401,370);
g.setColor(Color.MAGENTA);
g.drawString("-1", 30, 370);
g.drawString("0", 30, 270);
g.drawString("1", 30, 165);
g.drawString("¶/2", 115, 280);
g.drawString("¶", 205, 280);
g.drawString("3¶/2", 285, 280);
g.drawString("2¶", 405, 280);
g.drawLine(40, 40, 35, 55);
g.drawLine(35, 55, 45, 55);
g.drawLine(45, 55, 40, 40);
g.drawLine(450, 270, 425, 265);
g.drawLine(425, 265, 425, 275);
g.drawLine(425, 275, 450, 270);
g.setColor(Color.BLUE);
g.drawString("X", 460, 270);
g.drawString("Y-f(x)", 25, 35);
int ymax=this.getHeight();
int xmax=this.getWidth();
this.setSize(600, 500);
} }

miércoles, 20 de mayo de 2009

CICLO DE VIDA

Cuando un applet se inicia, se llaman en este orden a los siguientes métodos;

*init: Suele contener instrucciones para inicializar el applet.
*start: Como init, se suele usar para inicializar, pero con la diferencia de que este método también se llama cuando se reinicia un applet.
*paint: Se encarga de mostrar el contenido del applet. Se ejecuta cada vez que se tenga que redibujar.

Para terminar la ejecución o pausarse se llama a los siguientes métodos:

*stop: Suspende la ejecución del programa. Se llama cuando el applet se vuelve *temporalmente invisible.
*destroy: Cuando no se va a necesitar más el applet. Se usa para liberar recursos.

EJEMPLOS:
Applet TicTacToe.
Applet DrawTest.
Applet BarChart.
Applet Animator.
Applet ArcTest.
Applet Blink.
Applet Clock.
Applet GraphicsTest.
Applet ImageMap.
Applet MoleculeViewer.
Applet Zloden.

mruv y mruv en un applet

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Matriz Vo = new Matriz(1,3);
double aux = Double.parseDouble(jTextField8.getText());
Vo.matriz[0][0]= aux;
aux= Double.parseDouble(jTextField1.getText());
Vo.matriz[0][1]= aux;
aux= Double.parseDouble(jTextField10.getText());
Vo.matriz[0][2]= aux;

double t = Double.parseDouble(jTextField2.getText());

Matriz Xo = new Matriz(1,3);
aux = Double.parseDouble(jTextField9.getText());
Xo.matriz[0][0]= aux;
aux= Double.parseDouble(jTextField3.getText());
Xo.matriz[0][1]= aux;
aux= Double.parseDouble(jTextField11.getText());
Xo.matriz[0][2]= aux;

jTextArea1.setText(Xo.suma(Vo.multiplicaEscalar(t)).imprimir());
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Matriz Vo = new Matriz(1,3);
double aux = Double.parseDouble(jTextField4.getText());
Vo.matriz[0][0]= aux;
aux= Double.parseDouble(jTextField12.getText());
Vo.matriz[0][1]= aux;
aux= Double.parseDouble(jTextField13.getText());
Vo.matriz[0][2]= aux;

double t = Double.parseDouble(jTextField5.getText());

Matriz a = new Matriz(1,3);
aux = Double.parseDouble(jTextField7.getText());
a.matriz[0][0]= aux;
aux= Double.parseDouble(jTextField16.getText());
a.matriz[0][1]= aux;
aux= Double.parseDouble(jTextField17.getText());
a.matriz[0][2]= aux;

Matriz Xo = new Matriz(1,3);
aux = Double.parseDouble(jTextField6.getText());
Xo.matriz[0][0]= aux;
aux= Double.parseDouble(jTextField14.getText());
Xo.matriz[0][1]= aux;
aux= Double.parseDouble(jTextField15.getText());
Xo.matriz[0][2]= aux;

jTextArea3.setText(Xo.suma(Vo.multiplicaEscalar(t)).suma(a.multiplicaEscalar(t*t).multiplicaEscalar(0.5)).imprimir());
}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Matriz Vo = new Matriz(1,3);
double aux = Double.parseDouble(jTextField4.getText());
Vo.matriz[0][0]= aux;
aux= Double.parseDouble(jTextField12.getText());
Vo.matriz[0][1]= aux;
aux= Double.parseDouble(jTextField13.getText());
Vo.matriz[0][2]= aux;

double t = Double.parseDouble(jTextField5.getText());

Matriz a = new Matriz(1,3);
aux = Double.parseDouble(jTextField7.getText());
a.matriz[0][0]= aux;
aux= Double.parseDouble(jTextField16.getText());
a.matriz[0][1]= aux;
aux= Double.parseDouble(jTextField17.getText());
a.matriz[0][2]= aux;

Matriz Xo = new Matriz(1,3);
aux = Double.parseDouble(jTextField6.getText());
Xo.matriz[0][0]= aux;
aux= Double.parseDouble(jTextField14.getText());
Xo.matriz[0][1]= aux;
aux= Double.parseDouble(jTextField15.getText());
Xo.matriz[0][2]= aux;

jTextArea2.setText(Vo.suma(a.multiplicaEscalar(t)).imprimir());
}

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Matriz Vo = new Matriz(1,3);
double aux = Double.parseDouble(jTextField8.getText());
Vo.matriz[0][0]= aux;
aux= Double.parseDouble(jTextField1.getText());
Vo.matriz[0][1]= aux;
aux= Double.parseDouble(jTextField10.getText());
Vo.matriz[0][2]= aux;

double x=1;
jTextArea4.setText(Vo.multiplicaEscalar(x).imprimir());
}
}

APPLET

Un applet es un componente de una aplicación que se ejecuta en el contexto de otro programa, por ejemplo un navegador web. El applet debe ejecutarse en un contenedor, que lo proporciona un programa anfitrión, mediante un plugin, o en aplicaciones como teléfonos móviles que soportan el modelo de programación por applets.

A diferencia de un programa, un applet no puede ejecutarse de manera independiente, ofrece información gráfica y a veces interactúa con el usuario, típicamente carece de sesión y tiene privilegios de seguridad restringidos. Un applet normalmente lleva a cabo una función muy específica que carece de uso independiente. El término fue introducido en AppleScript en 1993.

Ejemplos comunes de applets son las Java applets y las animaciones Flash. Otro ejemplo es el Windows Media Player utilizado para desplegar archivos de video incrustados en los navegadores como el Internet Explorer. Otros plugins permiten mostrar modelos 3D que funcionan con una applet.

Un Java applet es un código JAVA que carece de un método main, por eso se utiliza principalmente para el trabajo de páginas web, ya que es un pequeño programa que es utilizado en una página HTML y representado por una pequeña pantalla gráfica dentro de ésta.

Por otra parte, la diferencia entre una aplicación JAVA y un applet radica en cómo se ejecutan. Para cargar una aplicación JAVA se utiliza el intérprete de JAVA (pcGRASP de Auburn University, Visual J++ de Microsoft, Forte de Sun de Visual Café). En cambio, un applet se puede cargar y ejecutar desde cualquier explorador que soporte JAVA (Netscape, Internet Explorer de Windows, Mozilla Firefox...etc).

martes, 12 de mayo de 2009

LIBRERIAS SWING Y AWT

LIBRERIA SWING
La librería de Componentes Swing Visual Java ofrece a los programadores unos componentes fácilmente integrables que permiten añadir atractivos estilos a botones, diálogos de color, campos de búsqueda y diseñar modernas y amigables interfaces gráficas de usuario para aplicaciones y applets Java. Es una plataforma independiente, Model-View-Controller Gui framework para Java. Sigue un simple modelo de programación por hilos, y posee las siguientes características principales:
Independencia de plataforma.
Extensibilidad: es una arquitectura altamente particionada: los usuarios pueden proveer sus propias implementaciones modificadas para sobrescribir las implementaciones por defecto. Se puede extender clases existentes proveyendo alternativas de implementación para elementos esenciales.
Customizable: dado el modelo de representación programático del framework de swing, el control permite representar diferentes 'look and feel' (desde MacOS look and feel hasta Windows XP look and feel). Más allá, los usuarios pueden proveer su propia implementación look and feel, que permitirá cambios uniformes en el look and feel existente en las aplicaciones Swing sin efectuar ningún cambio al código de aplicación.

Ventajas
El diseño en Java puro posee menos limitaciones de plataforma.
El desarrollo de componentes Swing es más activo.
Los componentes de Swing soportan más características.


LIBRERIA AWT
Se trata de una biblioteca de clases Java para el desarrollo de Interfaces de Usuario Gráficas. La versión del AWT que Sun proporciona con el JDK se desarrolló en sólo dos meses y es la parte más débil de todo lo que representa Java como lenguaje. El entorno que ofrece es demasiado simple, no se han tenido en cuenta las ideas de entornos gráficos novedosos. Quizá la presión de tener que lanzar algo al mercado haya tenido mucho que ver en la pobreza de AWT.

Javasoft, en vista de la precariedad de que hace gala el AWT, y para asegurarse que los elementos que desarrolla para generar interfaces gráficas sean fácilmente transportables entre plataformas, se ha unido con Netscape, IBM y Lighthouse Design para crear un conjunto de clases que proporcionen una sensación visual agradable y sean más fáciles de utilizar por el programador. Esta colección de clases son las Java Foundation Classes (JFC), que están constituidas por cinco grupos de clases, al menos en este momento: AWT, Java 2D, Accesibilidad, Arrastrar y Soltar y Swing.

La estructura básica del AWT se basa en Componentes y Contenedores. Estos últimos contienen Componentes posicionados a su respecto y son Componentes a su vez, de forma que los eventos pueden tratarse tanto en Contenedores como en Componentes, corriendo por cuenta del programador (todavía no hay herramientas de composición visual) el encaje de todas las piezas, así como la seguridad de tratamiento de los eventos adecuados. Con Swing se va un paso más allá, ya que todos los JComponentes son subclases de Container, lo que hace posible que widgets Swing puedan contener otros componentes, tanto de AWT como de Swing, lo que hace prever interesantes posibilidades.

HERENCIA

Herencia

public class Vector extends Matriz{

public Vector(){

}
public Vector(int numElementos){
numeroFilas=1;
numeroColumnas=numElementos;
matriz = new double[numeroFilas][numeroColumnas];
}
public Vector( int nF, int nC){
super(nF,nC);
}
public Matriz productoCruz(Vector X){

Matriz resultado;
resultado = X.transpueta();
resultado = this.multiplica(resultado);
return resultado;
}
public static void main (String [] args){

Vector v = new Vector(1,3);
v.matriz[0][0]=1;
v.matriz[0][1]=0;
v.matriz[0][2]=1;
//v.transpueta();
System.out.println(v.transpueta().imprimir());

Vector v1 = new Vector(1,3);
v1.matriz[0][0]=1;
v1.matriz[0][1]=2;
v1.matriz[0][2]=3;

Matriz respuesta;
respuesta=v.productoCruz(v1);

System.out.println(v1.transpueta().imprimir());
System.out.print(v.suma(v1).imprimir());
System.out.println("resultado del producto cruz\n"+respuesta.imprimir());
//System.out.print("producto escalar"+v.productoEscalar(v1));
}
}
APLICACIÓN:
public class OperacionesMatriz extends javax.swing.JFrame {
String aux="";
public OperacionesMatriz() {
initComponents();
}


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
double x1=Double.parseDouble(jTextField1.getText());
double y1=Double.parseDouble(jTextField2.getText());
double z1=Double.parseDouble(jTextField3.getText());
double x2=Double.parseDouble(jTextField4.getText());
double y2=Double.parseDouble(jTextField5.getText());
double z2=Double.parseDouble(jTextField6.getText());
Matriz v1 =new Matriz (1,3);
Matriz v2=new Matriz(1,3);
v1.matriz[0][0]=x1;v1.matriz[0][1]=y1;v1.matriz[0][2]=z1;
v2.matriz[0][0]=x2;v2.matriz[0][1]=y2;v2.matriz[0][2]=z2;
aux="El resultado de la suma es:\n";
aux+=(v1.suma(v2)).imprimir();
jTextArea1.setText(aux);

}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
double x1=Double.parseDouble(jTextField1.getText());
double y1=Double.parseDouble(jTextField2.getText());
double z1=Double.parseDouble(jTextField3.getText());
double x2=Double.parseDouble(jTextField4.getText());
double y2=Double.parseDouble(jTextField5.getText());
double z2=Double.parseDouble(jTextField6.getText());
Matriz v1 =new Matriz (1,3);
Matriz v2=new Matriz(1,3);
v1.matriz[0][0]=x1;v1.matriz[0][1]=y1;v1.matriz[0][2]=z1;
v2.matriz[0][0]=x2;v2.matriz[0][1]=y2;v2.matriz[0][2]=z2;
aux="El resultado de la resta es:\n";
aux+=(v1.resta(v2)).imprimir();
jTextArea1.setText(aux);
}



private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
double x1=Double.parseDouble(jTextField1.getText());
double y1=Double.parseDouble(jTextField2.getText());
double z1=Double.parseDouble(jTextField3.getText());
double x2=Double.parseDouble(jTextField4.getText());
double y2=Double.parseDouble(jTextField5.getText());
double z2=Double.parseDouble(jTextField6.getText());
Matriz v1 =new Matriz(1,3);
Matriz v2=new Matriz(1,3);
v1.matriz[0][0]=x1;v1.matriz[0][1]=y1;v1.matriz[0][2]=z1;
v2.matriz[0][0]=x2;v2.matriz[0][1]=y2;v2.matriz[0][2]=z2;


aux="El producto vectorial es:\n";
aux+=(v1.productoVectorial(v2)).imprimir();
jTextArea1.setText(aux);

}

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
double x1=Double.parseDouble(jTextField1.getText());
double y1=Double.parseDouble(jTextField2.getText());
double z1=Double.parseDouble(jTextField3.getText());
double x2=Double.parseDouble(jTextField4.getText());
double y2=Double.parseDouble(jTextField5.getText());
double z2=Double.parseDouble(jTextField6.getText());
Matriz v1 =new Matriz(1,3);
Matriz v2=new Matriz(1,3);
v1.matriz[0][0]=x1;v1.matriz[0][1]=y1;v1.matriz[0][2]=z1;
v2.matriz[0][0]=x2;v2.matriz[0][1]=y2;v2.matriz[0][2]=z2;

aux="El producto escalar es:\n";
aux+=(v1.productoEscalar(v2)).imprimir();
jTextArea1.setText(aux);

}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
double x1=Double.parseDouble(jTextField1.getText());
double y1=Double.parseDouble(jTextField2.getText());
double z1=Double.parseDouble(jTextField3.getText());
double x2=Double.parseDouble(jTextField4.getText());
double y2=Double.parseDouble(jTextField5.getText());
double z2=Double.parseDouble(jTextField6.getText());
Matriz v1 =new Matriz(1,3);
Matriz v2=new Matriz(1,3);
v1.matriz[0][0]=x1;v1.matriz[0][1]=y1;v1.matriz[0][2]=z1;
v2.matriz[0][0]=x2;v2.matriz[0][1]=y2;v2.matriz[0][2]=z2;


aux="El resultado del vector unitario es:\n";
aux+=v1.vectorUnitario().imprimir();
aux+=v.vectorUnitario().imprimir();
jTextArea1.setText(aux);

}

public class Matriz {

int numeroFilas;
int numeroColumnas;
double [][] matriz;

public Matriz(){}

public Matriz(int nF, int nC){
numeroFilas=nF;
numeroColumnas=nC;
matriz= new double[numeroFilas][numeroColumnas];

for(int i=0; i< numeroFilas; i++)
for(int j=0; j< numeroColumnas; j++)
matriz[i][j]=0;
}


public String imprimir(){
String aux = "";

for(int i=0; i for(int j=0; j aux= aux + matriz[i][j] + " ";
}
aux = aux + "\n";
}
return aux;
}

public Matriz productoEscalar(Matriz B){
if((this.numeroFilas==1)&(B.numeroFilas==1)&(this.numeroColumnas==3)&(B.numeroColumnas==3)){

Matriz r = new Matriz(this.numeroColumnas,this.numeroFilas);

for (int i = 0; i < this.numeroColumnas; i++)

r.matriz[0][i] += this.matriz[0][i]*B.matriz[0][i];
return r;
}
else{
Matriz r = new Matriz (1,1);
System .out.println("No se pueden obtener producto escalar");
return r;
}
}


public Matriz vectorUnitario(){
if((this.numeroFilas==1)&(this.numeroColumnas==3)){
Matriz r = new Matriz(1,3);

for (int i = 0; i < this.numeroColumnas; i++)

r.matriz[0][i] = this.matriz[0][i]/Math.sqrt((Math.pow(this.matriz[0][0],2)+Math.pow(this.matriz[0][1],2)+Math.pow(this.matriz[0][2],2)));
return r;
}

else{
Matriz r = new Matriz (1,1);
System .out.println("No se pueden obtener el vector unitario");
return r;
}
}




public Matriz productoVectorial(Matriz B){
if((this.numeroFilas==1)&(B.numeroFilas==1)&(this.numeroColumnas==3)&(B.numeroColumnas==3)){
Matriz r = new Matriz(this.numeroColumnas,this.numeroFilas);
r.matriz[0][0]=(this.matriz[0][1]*B.matriz[0][2])-(B.matriz[0][1]*this.matriz[0][2]);
r.matriz[0][1]=-(this.matriz[0][0]*B.matriz[0][2])-(B.matriz[0][0]*this.matriz[0][2]);
r.matriz[0][2]=(this.matriz[0][0]*B.matriz[0][1])-(B.matriz[0][0]*this.matriz[0][1]);


return r;
}
else{
Matriz r = new Matriz (1,1);
System .out.println("No se pueden obtener el Producto vectorial");
return r;
}
}


}

domingo, 19 de abril de 2009

CALCULO DEL MOVIMIENTO RECTILINEO UNIFORMEMENTE VARIADO

public class Matriz {
int numeroFilas;
int numeroColumnas;
double [][] matriz;

public Matriz(){}
public Matriz(int nF, int nC){
numeroFilas = nF;
numeroColumnas = nC;
matriz = new double[numeroFilas][numeroColumnas];
for(int i = 0; i < numeroFilas; i++)
for(int j = 0; j < numeroColumnas; j++)
matriz[i][j] = 0;
}

public String imprimir(){
String aux ="";

for(int i = 0; i < numeroFilas; i++){
for(int j = 0; j < numeroColumnas; j++){
aux = aux + matriz[i][j] +" ";
}
aux = aux + "\n";
}

return aux;
}


public String imprimir4(){
String aux ="";
aux="("+aux+ matriz[0][0]+"i"+" ";
aux=aux+matriz[0][1]+"j"+" ";
aux=aux+matriz[0][2]+"k"+")";
return aux;
}

public Matriz suma(Matriz B){
if((this.numeroFilas==B.numeroFilas)&(this.numeroColumnas==B.numeroColumnas)){
Matriz r =new Matriz(this.numeroFilas,this.numeroColumnas);
int j;
for(int i=0;i for(j=0;j r.matriz[i][j]=this.matriz[i][j]+B.matriz[i][j];

return r;
}
else{
Matriz r=new Matriz(1,1);
System.out.println("No se pueden sumar las matrices");
return r;

}
}

public Matriz resta(Matriz B){
if((this.numeroFilas==B.numeroFilas)&(this.numeroColumnas==B.numeroColumnas)){
Matriz r =new Matriz(this.numeroFilas,this.numeroColumnas);
int j;
for(int i=0;i for(j=0;j r.matriz[i][j]=this.matriz[i][j]-B.matriz[i][j];

return r;
}
else{
Matriz r=new Matriz(1,1);
System.out.println("No se pueden restar las matrices");
return r;
}
}
public Matriz multiplicacion(Matriz B){
if(this.numeroFilas==B.numeroColumnas){
Matriz r =new Matriz(this.numeroFilas,this.numeroColumnas);
int j;
int k;
for(int i=0;i
for(j=0;j for(k=0;k
r.matriz[i][j]+=this.matriz[i][k]*B.matriz[k][j];

return r;
}
else{
Matriz r=new Matriz(1,1);
System.out.println("multiplicacion no definida");
return r;
}
public Matriz multiplicaEscalar(double a){
Matriz r =new Matriz(this.numeroFilas,this.numeroColumnas);
int j;
for(int i=0;i
for( j=0;j
r.matriz[i][j]=this.matriz[i][j]*a;
return r;

}
}

public class MRUV {
public Particula particula;
public MRUV(){}
public MRUV(Matriz xo,Matriz vo,Matriz a){
particula=new Particula();
particula.setPosicionInicial(xo);
particula.setVelocidadInicial(vo);
particula.setAceleracion(a);
}
public Matriz calcularPosicion(double t){
Matriz posicion;
Matriz xo,vo,a;
xo=this.particula.getPosicionInicial();
posicion=new Matriz(xo.numeroFilas,xo.numeroColumnas);
vo=this.particula.getVelocidadInicial();
a=this.particula.getAceleracion();
posicion=xo.suma(vo.multiplicaEscalar(t));
posicion=posicion.suma(a.multiplicaEscalar(0.5*t*t));
return posicion;


}
public Matriz calculoVelocidad(double t){
Matriz posicion;
Matriz xo,vo,a,v;
xo=this.particula.getPosicionInicial();
posicion=new Matriz(xo.numeroFilas,xo.numeroColumnas);
vo=this.particula.getVelocidadInicial();
a=this.particula.getAceleracion();
v=vo.suma(a.multiplicaEscalar(t));
return v;
}
public Matriz calcularAceleracion(double t)
{

Matriz aceleracion=particula.getAceleracion();
return aceleracion;

}
public static void main(String args[]){
Matriz xo=new Matriz(1,3);
xo.matriz[0][0]=1;xo.matriz[0][1]=2;xo.matriz[0][2]=-5;
Matriz vo=new Matriz(1,3);
vo.matriz[0][0]=1;vo.matriz[0][1]=2;vo.matriz[0][2]=2;
Matriz a=new Matriz(1,3);
a.matriz[0][0]=2;a.matriz[0][1]=3;a.matriz[0][2]=4;
MRUV n=new MRUV(xo,vo,a);
Matriz x;
x=n.calcularPosicion(2);
Matriz v;
v=n.calculoVelocidad(2);
Matriz ac;
ac=n.calcularAceleracion(2);

System.out.println("POSICION INICIAL:\n"+xo.imprimir());
System.out.println("PSCON FINAL EN t=2:\n"+x.imprimir());

System.out.println("VEL. INICIAL:\n"+vo.imprimir());
System.out.println("VEL. FINAL EN t=2:\n"+v.imprimir());
System.out.println("ACELERACION:\n"+a.imprimir());}
{
}
}

lunes, 6 de abril de 2009

PRUEBA: JORGE CEVALLOS

PRIMERA PARTE
PRIMERA MATRIZ-----
-1
2
-3

SEGUNDA MATRIZ-----
1
0
1
0
0


SEGUNDA PARTE:
A+B = 4+2+4

A-B = 0+4+4

A'B =
4 -2 0
6 -3 0
8 -4 0

lunes, 30 de marzo de 2009

OPERACIONES CON MATRICES EN JAVA

public class Matriz {
int numeroFilas;
int numeroColumnas;
double [][] matriz;

public Matriz(){}
/**
* Constructor de matrices
* @param nF numero de filas
* @param nC numero de columnas
*/
public Matriz(int nF, int nC){
numeroFilas=nF;
numeroColumnas=nC;
matriz= new double[numeroFilas][numeroColumnas];

for(int i=0; i< numeroFilas; i++)
for(int j=0; j< numeroColumnas; j++)
matriz[i][j]=0;
}

/**
* Imprime los objetos de la clase matriz
* @return Un string que contien a la matriz
*/
public String imprimir(){
String aux = "";

for(int i=0; i for(int j=0; j aux= aux + matriz[i][j] + " ";
}
aux = aux + "\n";
}
return aux;
}

public String imprimir2(){
String aux ="";
aux=aux+"y1="+ matriz[0][0];
aux=aux+"\n";
aux=aux+"y2="+matriz[1][0];
return aux;
}

/**
* Metodo para sumar matrices
* @param B La matriz sumando
* @return Retorna otra matriz
*/
public Matriz suma(Matriz B){

if ((this.numeroFilas == B.numeroFilas)&(this.numeroColumnas==B.numeroColumnas)){
Matriz r = new Matriz(this.numeroFilas,this.numeroColumnas);
int j;
for(int i = 0; i < this.numeroFilas; i++)
for(j = 0; j r.matriz[i][j]=this.matriz[i][j]+B.matriz[i][j];
return r;
}
else{
Matriz r = new Matriz (1,1);
System .out.println("No se pueden sumar las matrices");
return r;
}
}

public Matriz resta(Matriz B){

if ((this.numeroFilas == B.numeroFilas)&(this.numeroColumnas==B.numeroColumnas)){
Matriz r = new Matriz(this.numeroFilas,this.numeroColumnas);
int j;
for(int i = 0; i < this.numeroFilas; i++)
for(j = 0; j r.matriz[i][j]=this.matriz[i][j]-B.matriz[i][j];
return r;
}
else{
Matriz r = new Matriz (1,1);
System .out.println("No se pueden restar las matrices");
return r;
}
}

public Matriz multiplica(Matriz B){
if(this.numeroFilas==B.numeroColumnas){
Matriz r = new Matriz(this.numeroFilas,this.numeroColumnas);
int j;
int k;
for(int i = 0; i < this.numeroFilas; i++)
for(j = 0; j for(k=0; k r.matriz[i][j]+=this.matriz[i][k]*B.matriz[k][j];
return r;
}
else{
Matriz r = new Matriz (1,1);
System .out.println("No se pueden multiplicar las matrices");
return r;
}
}

public Matriz clonar(){
Matriz r= new Matriz(this.numeroFilas, this.numeroColumnas);
int j;
for(int i = 0; i < this.numeroFilas; i++)
for(j = 0; j r.matriz[i][j]=this.matriz[i][j];
return r;
}
public Matriz transpueta(){
Matriz r = new Matriz(this.numeroColumnas,this.numeroFilas);
int j;
for (int i = 0; i < r.numeroFilas; i++)
for(j = 0; j < r.numeroColumnas;j++)
r.matriz[i][j] = this.matriz[j][i];
return r;
}

public Matriz inversa(){
Matriz result=new Matriz(this.numeroFilas,this.numeroColumnas);
double tmp;//variable temporal
Matriz I=new Matriz(this.numeroFilas,this.numeroColumnas*2);
for(int i = 0; i for(int j = 0; j I.matriz[i][j]=0.0;


for(int i = 0; i for(int j = 0; j I.matriz[i][j]=this.matriz[i][j];
if (i==j)
I.matriz[i][j+this.numeroFilas]=1.0;
}
}

for(int i=0; i<(this.numeroFilas); i++){
tmp=I.matriz[i][i];
for(int j=0;j<(this.numeroColumnas*2);j++)
I.matriz[i][j]/=tmp;
for(int k=0;k if(k!=i){
tmp=I.matriz[k][i];
for(int j=0;j<(this.numeroColumnas*2);j++)
I.matriz[k][j]-=tmp*I.matriz[i][j];
}
}
}

for(int i = 0; i < this.numeroFilas; i++)
for(int j = 0; j result.matriz[i][j]=I.matriz[i][j+this.numeroColumnas];
return result;
}


public static void main(String args[]){
Matriz m= new Matriz(3, 3);
m.matriz[0][0]=1;
m.matriz[1][1]=3;
m.matriz[2][2]=5;
System.out.println("LA MATRIZ M ES: ");
System.out.println(m.imprimir());
Matriz copia;
copia= m;
System.out.println("LA COPIA DE M ES: ");
System.out.println(copia.imprimir());
m.matriz [0][0]= 100;
System.out.println("LA MATRIZ M MODIFICADA ES: ");
System.out.println(m.imprimir());
System.out.println("LA COPIA DE M MODIFICADA ES: ");
System.out.println(copia.imprimir());
copia=m.clonar();
m.matriz [0][0]= 1;
System.out.println("LA MATRIZ M ES: ");
System.out.println(m.imprimir());
System.out.println("LA MATRIZ CLON DE M ES: ");
System.out.println(copia.imprimir());


Matriz b = new Matriz(3,3);
b.matriz[0][0] = 1; b.matriz[0][1]=2; b.matriz[0][2]=3;
b.matriz[1][1] = 4; b.matriz[1][2] = 5;
b.matriz[2][2] = 6;
System.out.println(b.imprimir());

Matriz resultado;
resultado = m.suma(b);
System.out.println("LA SUMA ES: ");
System.out.println(resultado.imprimir());

resultado = m.resta(b);
System.out.println("LA RESTA ES: ");
System.out.println(resultado.imprimir());

resultado = b.transpueta();
System.out.println("LA TRANSPUESTA DE B ES: ");
System.out.println(resultado.imprimir());

resultado = m.transpueta();
System.out.println("LA TRANSPUESTA DE M ES: ");
System.out.println(resultado.imprimir());

resultado = m.multiplica(b);
System.out.println("LA MULTILPLICACION ES: ");
System.out.println(resultado.imprimir());

resultado=m.inversa();
System.out.println("LA INVERSA DE M ES: ");
System.out.println(resultado.imprimir());

resultado=b.inversa();
System.out.println("LA INVERSA DE B ES: ");
System.out.println(resultado.imprimir());

Matriz d=new Matriz(2,2);
d.matriz[0][0]=1;d.matriz[0][1]=1;
d.matriz[1][0]=-1;d.matriz[1][1]=2;
System.out.println("LA MATRIZ D ES: ");
System.out.println(d.imprimir());

Matriz c=new Matriz(2,2);
c.matriz[0][0]=1;
c.matriz[1][0]=0;
System.out.println("LA MATRIZ C ES: ");
System.out.println(c.imprimir());

Matriz resultante;
resultante=d.inversa();
System.out.println("LA INVERSA DE D:");
System.out.println(resultado.imprimir());

resultante=d.multiplica(c);
System.out.println("LA MULTIPLICACIÓN DE D Y C ES: ");
System.out.println(resultado.imprimir());

resultante=d.inversa().multiplica(c);
System.out.println("LA MULTIPLICACIÓN CON LA INVERSA DE D ES: ");
System.out.println(resultado.imprimir2());


}

}

domingo, 22 de marzo de 2009

EJERCICIOS DE MATRICES

public static void main(String[]args)
{
int[]a= new int[5];
int[]b= new int[5];
int[]c= new int[5];
int answ; int answ1;

a[0]=1;
a[1]=1;
a[2]=9;
a[3]=9;
a[4]=2;
b[0]=3;
b[1]=2;
b[2]=4;
b[3]=2;
b[4]=2;

//Sumar matrices a[]+b[]
for(int i= 4; i>2; i--)
{
c[i]= a[i] + b[i];
answ=c[i];
if(answ>= 10)
c[i]= answ-10;
}

// Número que divide en 2 partes las matrices
for(int i= 2; i>0; i--)
{
c[i]= a[i]+b[i]+(a[i+1]%b[i+1]);
answ1= c[i];

if(answ1>= 10)
c[i]= answ1-10;
}
c[0]= a[0]+b[0];
for(int i= 0; i<5; i++)
System.out.print(c[i]);
}
}

PROGRAMACIO ORIEBTADA A OBJETOS

La programación Orientada a objetos (POO) es una forma especial de programar, más cercana a como expresaríamos las cosas en la vida real que otros tipos de programación. La POO no es difícil, pero es una manera especial de pensar, a veces subjetiva de quien la programa, de manera que la forma de hacer las cosas puede ser diferente según el programador. Aunque podamos hacer los programas de formas distintas, no todas ellas son correctas, lo difícil no es programar orientado a objetos sino programar bien. Programar bien es importante porque así nos podemos aprovechar de todas las ventajas de la POO.
Los objetos son entidades que combinan estado, comportamiento e identidad:
*El estado está compuesto de datos, será uno o varios atributos a los que se habrán asignado unos valores concretos (datos).
*El comportamiento está definido por los procedimientos o métodos con que puede operar dicho objeto, es decir, qué operaciones se pueden realizar con él.
*La identidad es una propiedad de un objeto que lo diferencia del resto, dicho con otras palabras, es su identificador (concepto análogo al de identificador de una variable o una constante).
La programación orientada a objetos expresa un programa como un conjunto de estos objetos, que colaboran entre ellos para realizar tareas.

lunes, 16 de marzo de 2009

ARREGLOS EN JAVA

El tipo llamado arreglo o en inglés array, es el tipo más conocido y en muchos lenguajes, el único tipo de datos estructurados que se ha implementado. Un tipo arreglo es una lista de datos con un número fijo de componentes, todos del mismo tipo denominado tipo base; los que son referenciados o calificados mediante índices o expresiones ordinales encerradas en corchetes, que actúan como prefijo al identificador del arreglo, siendo su tipo denominado tipo índice.
Algunas de sus características son las siguientes.-
*Los arreglos se crean con el operador new seguido del tipo y número de elementos.
*Se puede acceder al número de elementos de un arreglo con la variable miembro implícita length (por ejemplo, vect.length).
*Se accede a los elementos de un array con los corchetes y un índice que varía de 0 a length-1.
*Se pueden crear arreglos de objetos de cualquier tipo. En principio un arreglo de objetos es un arreglo de referencias que hay que completar llamando al operador new.
*Los elementos de un arreglo se inicializan al valor por defecto del tipo correspondiente (cero para valores numéricos, la cadena vacía para Strings, false para boolean, null para referencias).
*Como todos los objetos, los arreglos se pasan como argumentos a los métodos por referencia.
*Se pueden crear arreglos anónimos (por ejemplo, crear un nuevo arreglo como argumento actual en la llamada a un método).
Declaración de Arreglos.-
Como otras variables, antes de poder utilizar un arreglo primero se debe declarar. De nuevo, al igual que otras variables, la declaración de un arreglo tiene dos componentes primarios: el tipo del arreglo y su nombre. Un tipo de arreglo incluye el tipo de dato de los elementos que va contener el arreglo. Por ejemplo, el tipo de dato para un arreglo que sólo va a contener elementos enteros es un arreglo de enteros. No puede existir un arreglo de tipo de datos genérico en el que el tipo de sus elementos esté indefinido cuando se declara el arreglo. Aquí tienes la declaración de un arreglo de enteros:

int[ ] arrayDeEnteros;


La parte int[ ] de la declaración indica que arrayDeEnteros es un arreglo de enteros. La declaración no asigna ninguna memoria para contener los elementos del arreglo. Si se intenta asignar un valor o acceder a cualquier elemento de arrayDeEnteros antes de haber asignado la memoria para él, el compilador dará un error como este y no compilará el programa:

testing.java:64: Variable arrayDeEenteros may not have been initialized.

Para asignar memoria a los elementos de un arreglo, primero se debe ejemplarizar el arreglo. Se puede hacer esto utilizando el operador new de Java. (Realmente, los pasos que se deben seguir para crear un arreglo son similares a los se deben seguir para crear un objeto de una clase: declaración, ejemplificación e inicialización. La siguiente sentencia asigna la suficiente memoria para que arrayDeEnteros pueda contener diez enteros.

int[ ] arrayDeEnteros = new int[10]

En general, cuando se crea un arreglo, se utiliza el operador new, más el tipo de dato de los elementos del arreglo, más el número de elementos deseados encerrado entre corchetes cuadrados ([ y ]).
TipodeElemento[ ] NombredeArray = new TipodeElementos[tamanoArray]Ahora que se ha asignado memoria para un arreglo ya se pueden asignar valores a los elementos y recuperar esos valores:

for (int j = 0; j < arrayDeEnteros.length; j ++)
{
arrayDeEnteros[j] = j;
System.out.println("[j] = " + arrayDeEnteros[j]);
}


Como se puede ver en el ejemplo anterior, para referirse a un elemento del arreglo, se añade corchetes cuadrados al nombre del arreglo. Entre los corchetes cuadrados se indica (bien con una variable o con una expresión) el índice del elemento al que se quiere acceder. Observa que en Java, el índice del arreglo empieza en 0 y termina en la longitud del arreglo menos uno.
Hay otro elemento interesante en el pequeño ejemplo anterior. El bucle for itera sobre cada elemento de arrayDeEnteros asignándole valores e imprimiendo esos valores. Observa el uso de arrayDeEnteros.length para obtener el tamaño real del arreglo.
length es una propiedad proporcionada para todos los arreglo de Java. Los arreglo pueden contener cualquier tipo de dato legal en Java incluyendo los tipos de referencia como son los objetos u otros arreglos. Por ejemplo, el siguiente ejemplo declara un arreglo que puede contener diez objetos String.

String[ ] arrayDeStrings = new String[10];

Los elementos en este arreglo son del tipo referencia, esto es, cada elemento contiene una referencia a un objeto String. En este punto, se ha asignado suficiente memoria para contener las referencias a los Strings, pero no se ha asignado memoria para los propios Strings. Si se intenta acceder a uno de los elementos de arraydeStrings obtendrá una excepción 'NullPointerException' porque el arreglo está vacío y no contiene ni cadenas ni objetos String. Se debe asignar memoria de forma separada para los objetos String:

for (int i = 0; i < arraydeStrings.length; i ++)
{
arraydeStrings[i] = new String("Hola " + i);
}


NOTA.- Los arreglos son entidades estáticas, cuyo primer elemento se encuentra en el índice 0

domingo, 15 de marzo de 2009

OPERACIONES CON DOS VECTORES EN JAVA

AQUI LES DEJO EL COD. DE UN PROGRAMA QUE REALIZA OPERACIONES CON VECTORES DE TRES COORDENADAS: SUMA, RESTA, PROD. ESCALAR, UNITARIOS DE C/U, ANGULO FORMADO POR LOS DOS, Y MAGNITUD O MODULO DE C/U....
---------------------------------------------------------------------------
public static void main(String[] args) {
double [] a= new double[3];
double [] b= new double[3];
double [] c= new double[3];
int suma;
int resta;
int escalar;
double cruz;
double mag;
double mag2;
double angulo;
double ang;
double ang2;
a[0]=2; a[1]=6; a[2]=4;
b[0]=1; b[1]=3; b[2]=2;

//SUMA
for(int i=0; i<3; i++)
c[i]= a[i] + b[i];
for(int i=0; i<3; i++)
System.out.println("LA SUMA ES--> "+c[i]);

//RESTA
for(int i=0; i<3; i++)
c[i]= a[i] - b[i];
for(int i=0; i<3; i++)
System.out.println("LA RESTA ES--> "+c[i]);

//PROD. ESCALAR
escalar = 0;
for(int i=0; i<3; i++){
escalar += a[i] * b[i];
}
System.out.println("EL PRODUCTO ESCALAR ES--> "+ escalar);

//UNITARIOS
for(int i=0; i<3; i++)
c[i] = a[i]/escalar;
for(int i=0; i<3; i++)
System.out.println("EL UNITARIO DE A ES--> "+c[i]);
for(int i=0; i<3; i++)
c[i] = b[i]/escalar;
for(int i=0; i<3; i++)
System.out.println("EL UNITARIO DE B ES--> "+c[i]);


//ANGULO
ang= Math.sqrt(Math.pow(a[0],2)+Math.pow(a[1],2)+Math.pow(a[2],2));
ang2= Math.sqrt(Math.pow(b[0],2)+Math.pow(b[1],2)+Math.pow(b[2],2));
angulo= Math.acos(escalar/(ang*ang2));
System.out.println("EL ANGULO FORMADO POR LOS 2 VECTORES ES--> "+ angulo);

//MAGNITUD
mag= Math.sqrt(Math.pow(a[0],2)+Math.pow(a[1],2)+Math.pow(a[2],2));
System.out.println("LA MAGNITUD DEL VECTOR A ES--> "+mag);
mag2= Math.sqrt(Math.pow(b[0],2)+Math.pow(b[1],2)+Math.pow(b[2],2));
System.out.println("LA MAGNITUD DEL VECTOR B ES--> "+mag2);

//PROD. CRUZ
cruz = (((a[1] *b[2]) - (a[2] *b[1])) - ((a[0] *b[2]) - (b[0] *a[2])) +
((a[0] *b[1]) - (b[0] *a[1])));
System.out.println("El valor cruz es: " +cruz);
---------------------------------------------------------------------------

martes, 10 de marzo de 2009

AQUI LES DEJO LO QUE ES L JDK Y EL JRE

CONTINUANDO CON JAVA, AQUI PONGO A SU DISPOSICION LO QUE ES EL JDK Y JRE:
JRE.- Por sus siglas en ingles (JAVA Runtime Environment) que significa en español (Entorno en Tiempo de Ejecución de JAVA). Es el software necesario para ejecutar cualquier aplicación desarrollada para la plataforma JAVA. El usuario final usa el JRE como parte de paquetes software o plugins en un navegador Web.
JDK-. JAVA ofrece también el SDK de JAVA 2, o JDK por sus siglas en ingles (JAVA Development Kit) que significa en español (Paquete de Desarrollo de JAVA) en cuyo reside el JRE, mencionado antes, e incluye herramientas como el compilador de JAVA, Javadoc para generar documentación o el depurador. Este se lo puede también obtener como un paquete independiente, y puede considerarse como el entorno necesario para ejecutar una aplicación JAVA, mientras que un desarrollador debe además contar con otras facilidades que ofrece el JDK.

JAVA

1. ¿QUÉ ES?
Java es un lenguaje de programación orientado a objetos, y en el que se puede realizar cualquier tipo de programa, este lenguaje trabaja igual independientemente de la plataforma que usemos, incluso para distintos tipos de dispositivos móviles, agendas, etc. Este lenguaje permite jugar en línea, participar en sesiones de chat, calcular los intereses de una hipoteca y ver imágenes en tres dimensiones, etc. Es de vital importancia para las aplicaciones de intranet y otras soluciones de comercio electrónico que constituyen la base informática de las empresas.
2. HISTORIA
Nació gracias a la compania Sun Mycrosystems en 1991. Este contiene sintaxis de otros lenguajes como son el C y el C++, pero el modelo de objetos de JAVA es muchísimo más simple eliminando también algunas herramientas de los anteriores, así evitando errores, como la manipulación directa de punteros o memoria. Hoy en día es un lenguaje muy extendido el cual tiene gran importancia a nivel mundial.