Está en la página 1de 33

PROGRAMACION II

INTEGRANTES:
JOHN LEIVA
LENIN GOMEZ
CUADERNO DE PROGRAMACION
II SEGUNDO PARCIAL
ENERO 201
Captulo 3: Recursividad----------------------------------------------------------------------3
Captulo 4: Arrays (Arreglos)-----------------------------------------------------------------4

Contenido

Captulo 3: Recursividad................................................................................. 3
Captulo 4: Arrays (Arreglos)..........................................................................4
Captulo 5: Agregacin y Composicion...........................................................4
DEBERES..................................................................................................... 7
EJERCICIOS................................................................................................... 14

Captulo 3: Recursividad
3.1 Defi nicin:
Primero debemos decir que la recursividad no es una estructura de datos,
sino que es una tcnica de programacin que nos permite que un bloque de
instrucciones se ejecute n veces. Remplaza en ocasiones a estructuras
repetitivas.
La recursividad es un concepto difcil de entender en principio, pero luego
de analizar diferentes problemas aparecen puntos comunes.
En Java los mtodos pueden llamarse a s mismos. Si dentro de un mtodo
existe la llamada a s mismo decimos que el mtodo es recursivo.
Cuando un mtodo se llama a s mismo, se asigna espacio en la pila para las
nuevas variables locales y parmetros.
Al volver de una llamada recursiva, se recuperan de la pila las variables
locales y los parmetros antiguos y la ejecucin se reanuda en el punto de
la llamada al mtodo.

3.2 Ejemplo:
Por ejemplo, para escribir un mtodo que calcule el factorial de un nmero entero
no negativo, podemos hacerlo a partir de la definicin de factorial:
Si n = 0 entonces
0! = 1
si n>0 entonces
n! = n * (n1) * (n2) * ... * 3 * 2 * 1
Esto dar lugar a una solucin iterativa en Java mediante un bucle for:
// Mtodo Java no recursivo para calcular el factorial de un nmero
public double factorial(int n){
double fact=1;
int i;
if (n==0)
fact=1;
else
for(i=1;i<=n;i++)
fact=fact*i;
return fact;
}
Pero existe otra definicin de factorial en funcin de s misma:
0! = 1

n! = n (n 1)! , si n > 0 (El factorial de n es n por el factorial de n-1)


Esta definicin da lugar a una solucin recursiva del factorial en Java:
// Mtodo Java recursivo para calcular el factorial de un nmero
public double factorial(int n){
if (n==0)
return 1;
else
return n*(factorial(n-1));
}

Captulo 4: Arrays (Arreglos)


4.1 Defi nicin:
Array(lista o tabla) es una secuencia de datos del mismo tipo. Los datos se
llaman elementos del array y se numeran consecutivamente (0,1,2,...,n). El
tipo de elemento almacenado en el array puede ser de cualquier tipo de
dato definido en java.
Como entero, flotante, string, etc; incluyendo estructuras definidas por el
usuario y objetos, como se describiran mas adelante.
Los elementos de un array se numeran consecutivamente; y los valores
numricos se denominan valores ndice o subndice del array. El termino
subndice se utiliza al igual que en las matemticas para definir secuencias
de nmeros como A0, A1, A2,..., An.
Estos nmeros localizan la posicin de los elementos del array,
proporcionando acceso directo al array. Cada ndice o subndice del array
define un casillero o un dato elemento.

4.2 Declaracion de un Array

Sintaxis:
C/C++
tipo[] nombre = new tipo[tamao];
int[] a = new int[10];
int a[10];
float[] fData = new float[40];
float fData[40];
String[] sData = new String[100];
char*sData;
char sData[100];
String sData[100];(crear la clase
String en C++)

4.3 Almacenamiento en memoria de los Arrays


[0]----------------------------- [9](ndice)
_ _ _ _ _ _ _ _ _ _
A |7|5|2|1|6|9|6|2|3|4|->celda (dato)

[1000]........................ [1018] espacio representacin en memoria


(Nombre)
A [0]=7; A[1]=5-> se asigna por ndice de forma manual o automtica
(bucles).
El espacio de almacenamiento depende del tipo de dato.

Captulo 5: Agregacin y Composicion


5.1 Agregacin
5.1.1 Defi nicion:
La agregacin es un tipo de asociacin que indica que una clase es parte de
otra clase (composicin dbil). Los componentes pueden ser compartidos
por varios compuestos (de la misma asociacin de agregacin o de varias
asociaciones de agregacin distintas). La destruccin del compuesto no
conlleva la destruccin de los componentes. Habitualmente se da con
mayor frecuencia que la composicin.
La agregacin se representa en UML mediante un diamante de color blanco
colocado en el extremo en el que est la clase que representa el todo.
Veamos un ejemplo de agregacin:

Tenemos una clase Empresa.


Tenemos una clase Cliente.
Una empresa agrupa a varios clientes.

5.2 Composicion
5.2.1 Defi nicion:
Composicin es una forma fuerte de composicin donde la vida de la clase
contenida debe coincidir con la vida de la clase contenedor. Los

componentes constituyen una parte del objeto compuesto. De esta forma,


los componentes no pueden ser compartidos por varios objetos compuestos.
La supresin del objeto compuesto conlleva la supresin de los
componentes.
El smbolo de composicin es un diamante de color negro colocado en el
extremo en el que est la clase que representa el todo (Compuesto).
Veamos un ejemplo de composicin:

Tenemos una clase Empresa.


Un objeto Empresa est a su vez compuesto por uno o varios objetos del
tipo empleado.
El tiempo de vida de los objetos Empleado depende del tiempo de vida de
Empresa, ya que si no existe una Empresa no pueden existir sus empleados.

5.3 Diferencias entre Composicin y Agregacin


La siguiente tabla intenta resumir algunas

diferencias entre agregacin y composicin.

5.4 En cdigo
Para traducir ambas relaciones a cdigo, podemos utilizar un atributo en la
clase contenedora o compuesta donde almacenaremos una coleccin de los
objetos que la componen, y por otro lado declararemos un mtodo para
agregar elementos a la coleccin. Dependiendo del lenguaje de
programacin empleado, podemos utilizar diferentes estructuras de datos
que nos permitan almacenar esa coleccin de objetos, aunque
generalmente se utilizan arrays (arreglos) para este fin.
Veamos un ejemplo:

Como podemos apreciar, es tan simple como crear en la clase Empresa un


atributo clientes (coleccin de clientes) que sea un array, luego creamos un
mtodo addCliente donde recibiremos objetos de tipo Cliente y los
agregaremos dentro del array.

DEBERES
Program.java
package jappmatrices;
public class Program {
public static void main(String[] args) {
// TODO code application logic here
MatrixJ A = new MatrixJ();
MatrixJ AT = new MatrixJ();

A.Print();
System.out.printf("\n");
AT.Print();
System.out.printf("\n");
A.Read();
A.Print();
System.out.printf("\n");
//AT = A.Transpose();
AT = A.Transpose(A);
AT.Print();
System.out.printf("\n");
A.OrdenarMatrizFilas();
A.Print();
}
}

MatrixJ.java
package jappmatrices;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MatrixJ
{
int [][] M = new int[4][4];
int [] V = new int[16];
public MatrixJ()
{
int i,j;
for(i=0; i<M.length; i++)
{
for(j=0;j<M.length;j++)
M[i][j] = -1;
}
for(i=0; i<V.length; i++)
V[i] = -1;
}
public void Print()
{
int i, j;
for (i=0; i<M.length;i++)
{
System.out.printf("\n");
for(j=0; j<M.length; j++)
{
System.out.printf("%d\t", M[i][j]);
}
}

}
public MatrixJ Transpose(MatrixJ P)
{
MatrixJ T = new MatrixJ();
int i, j;
for (i=0; i < P.M.length;i++)
{
System.out.printf("\n");
for(j=0; j < P.M.length; j++)
{
T.M[j][i] = P.M[i][j];
}
}
return(T);
}
public MatrixJ Transpose()
{
MatrixJ T = new MatrixJ();
int i, j;
for (i=0; i<M.length;i++)
{
System.out.printf("\n");
for(j=0; j<M.length; j++)
{
T.M[j][i] = M[i][j];
}
}
return(T);
}
public void OrdenarArreglo()
{
int actual, sig, temp;
for(actual = 0; actual < V.length; actual++)
{
for(sig = actual+1; sig < V.length; sig++)
{
if(V[actual] > V[sig])
{
temp = V[actual];
V[actual] = V[sig];
V[sig] = temp;
}
}
}
}
public void CopiarDatosMatrizArreglo()
{
int i, j, k;
for(i = 0, k = 0; i < M.length; i++)
{

for(j = 0; j < M.length; j++, k++)


{
V[k] = M[i][j];
}
}
}
public void CopiarDatosArregloMatriz()
{
int i, j, k;
for(i = 0, k = 0; i < M.length; i++)
{
for(j = 0; j < M.length; j++, k++)
{
M[i][j] = V[k];
}
}
}
public void OrdenarMatrizFilas()
{
this.CopiarDatosMatrizArreglo();
this.OrdenarArreglo();
this.CopiarDatosArregloMatriz();
}
public void Read()
{
int i, j;
String sData = "";
for (i=0; i<M.length;i++)
{
System.out.printf("\n");
for(j=0; j<M.length; j++)
{
try
{
System.out.printf("Ingrese un valor en el
casillero [%d][%d]: ", i, j);
InputStreamReader isr = new
InputStreamReader(System.in);
BufferedReader streamInput = new
BufferedReader(isr);
sData = streamInput.readLine();
M[i][j] = (Integer.parseInt(sData));
}
catch(IOException e)
{
System.err.println("Error: " + e.getMessage());
}
}
}
}

}
package JAppArrayStructured;
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
int[] claseInutil = new int[10];
readData(claseInutil);
printData(claseInutil);
}
public static void readData(int[] p) {
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
System.out.printf("Ingrese el dato %d: ", i+1);
p[i] = sc.nextInt();
}
}
public static void printData(int[] p) {
for (int i = 0; i < 10; i++) {
System.out.printf("%d\n", p[i]);
}
}
public static void ordenarArreglo(int[] p) {
int[] tmp = p;
for (int i = 9; i >= 0; i--)
p[10-i-1] = tmp[i];
}
}

Realizar las operaciones de suma, resta, multiplicacin y calcular la matriz inversa.


package Deberes;
public class OperacionesMatrices {
public static void main(String args[]) {
int matriz1[][] = {{1, 5},
{3, 7}};
int matriz2[][] = {{4, 5},
{1, 9}};
System.out.printf("Operaciones entre matriz A:\n");
imprimir_matriz(matriz1);
System.out.printf("Y matriz B:\n");
imprimir_matriz(matriz2); System.out.printf("\n");
sumar_dos_matrices(matriz1, matriz2);
restar_dos_matrices(matriz1, matriz2);
multiplicar_dos_matrices(matriz1, matriz2);
calcular_matriz_inversa(matriz1);
}
public static void sumar_dos_matrices(int matriz1[][],
int matriz2[][]) {
System.out.printf("Suma de matrices:\n");
if((matriz1.length == matriz2.length) &&
(matriz1[0].length == matriz2[0].length)) {
int filas = matriz1.length; int columnas =
matriz1[0].length;
int matriz[][] = new int[filas][columnas];
for(int i = 0; i < filas; i++)
for(int j = 0; j < columnas; j++)
matriz[i][j] = matriz1[i][j] + matriz2[i][j];
imprimir_matriz(matriz);
} else
System.out.printf("\tLas matrices difieren en filas y "
+
"columnas\n");
}
public static void restar_dos_matrices(int matriz1[][],
int matriz2[][]) {
System.out.printf("Resta de matrices:\n");
if((matriz1.length == matriz2.length) &&
(matriz1[0].length == matriz2[0].length)) {
int filas = matriz1.length; int columnas =
matriz1[0].length;
int matriz[][] = new int[filas][columnas];
for(int i = 0; i < filas; i++)
for(int j = 0; j < columnas; j++)
matriz[i][j] = matriz1[i][j] - matriz2[i][j];
imprimir_matriz(matriz);
} else
System.out.printf("\tLas matrices difieren en filas y "
+
"columnas\n");
}
public static void multiplicar_dos_matrices(int matriz1[][],
int matriz2[][]) {
System.out.printf("Multiplicacin de matrices:\n");

if(matriz1[0].length == matriz2.length) {
int filas1 = matriz1.length;
int filas2 = matriz2.length;
int columnas2 = matriz2[0].length;
int matriz[][] = new int[filas1][columnas2];
int resultado = 0;
for(int i = 0; i < filas1; i++)
for(int j = 0; j < columnas2; j++) {
for(int k = 0; k < filas2; k++)
resultado += (matriz1[i][k]*matriz2[k][j]);
matriz[i][j] = resultado; resultado = 0;
}
imprimir_matriz(matriz);
} else
System.out.printf("\tNo es posible multiplicar\n");
}
public static void calcular_matriz_inversa(int matriz[][]) {
System.out.printf("Matriz inversa:\n");
int filas = matriz.length, columnas = matriz[0].length;
int matrizInversa[][] = new int[columnas][filas];
for(int i = 0; i < filas; i++)
for(int j = 0; j < columnas; j++)
matrizInversa[j][i] = matriz[i][j];
imprimir_matriz(matrizInversa);
}
public static void imprimir_matriz(int matriz[][]) {
int filas = matriz.length; int columnas = matriz[0].length;
for(int i = 0; i < filas; i++) {
for(int j = 0; j < columnas; j++)
System.out.printf("%d\t", matriz[i][j]);
System.out.printf("\n");
}
}
}

EJERCICIOS
Clase Vector:
package javaappspaceshipsgame;
import java.io.*;
public class Vector3D
{
private float mX, mY, mZ;
public float getX()
{ return mX; }
public void setX(float mX)
{ this.mX = mX; }
public float getY()
{ return mY; }
public void setY(float mY)
{ this.mY = mY; }
public float getZ()
{ return mZ; }
public void setZ(float mZ)
{ this.mZ = mZ; }
public Vector3D()
{
setX(0.0f); setY(0.0f); setZ(0.0f);
}
public Vector3D(float[] coords)
{
setX(coords[0]); setY(coords[1]); setZ(coords[2]);
}
public Vector3D(float x, float y, float z)
{
setX(x); setY(y); setZ(z);
}
public boolean Equals(Vector3D rhs)
{
return(getX() == rhs.getX() && getY() == rhs.getY() &&
getZ() == rhs.getZ());
}
public Vector3D Addition(Vector3D rhs)
{
Vector3D Temp = new Vector3D();
Temp.setX(getX() + rhs.getX());
Temp.setY(getY() + rhs.getY());
Temp.setZ(getZ() + rhs.getZ());

return Temp;
}
public Vector3D Subtraction(Vector3D rhs)
{
Vector3D Temp = new Vector3D();
Temp.setX(getX() - rhs.getX());
Temp.setY(getY() - rhs.getY());
Temp.setZ(getZ() - rhs.getZ());
return Temp;
}
public Vector3D ScalarMultiplication(float scalar)
{
Vector3D P = new Vector3D();
P.setX(getX() * scalar);
P.setY(getY() * scalar);
P.setZ(getZ() * scalar);
return P;
}
public float Lenght()
{
return((float)Math.sqrt(getX() * getX() + getY() * getY() +
getZ() * getZ()));
}
public void Normalize()
{
float len = Lenght();
setX(getX() / len); setY(getY() / len); setZ(len);
}
public float DotProduct(Vector3D rhs)
{
float DotP = getX() * rhs.getX() + getY() * rhs.getY() +
getZ() * rhs.getZ();
return DotP;
}
public void Print()
{
System.out.printf("< %f, %f, %f > \n", getX(), getY(),
getZ());
}
public void Input()
{
String sData = "";
try
{
System.out.printf("Ingrese x: ");
InputStreamReader isr = new
InputStreamReader(System.in);

BufferedReader streamInput = new BufferedReader(isr);


sData = streamInput.readLine();
setX(Float.parseFloat(sData));
}
catch(IOException e)
{
System.err.println("Error: " + e.getMessage());
}
try
{
System.out.printf("Ingrese y: ");
InputStreamReader isr = new
InputStreamReader(System.in);
BufferedReader streamInput = new BufferedReader(isr);
sData = streamInput.readLine();
setY(Float.parseFloat(sData));
}
catch(IOException e)
{
System.err.println("Error: " + e.getMessage());
}
try
{
System.out.printf("Ingrese z: ");
InputStreamReader isr = new
InputStreamReader(System.in);
BufferedReader streamInput = new BufferedReader(isr);
sData = streamInput.readLine();
setZ(Float.parseFloat(sData));
}
catch(IOException e)
{
System.err.println("Error: " + e.getMessage());
}
}
}

Clase SpaceShip
package javaappspaceshipsgame;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
* @author Admin
*/
public class SpaceShip
{
private String mFirstName;
private String mLastName;
private int mFuelLevel;
private int mDamage;
private Vector3D mPosicion = new Vector3D(0.0f, 0.0f, 0.0f);
private Vector3D mVelocity = new Vector3D(1.0f, 1.0f, 1.0f);

/**
* @return the mFirstName
*/
public String getmFirstName() {
return mFirstName;
}
/**
* @param mFirstName the mFirstName to set
*/
public void setmFirstName(String mFirstName) {
this.mFirstName = mFirstName;
}
/**
* @return the mLastName
*/
public String getmLastName() {
return mLastName;
}
/**
* @param mLastName the mLastName to set
*/
public void setmLastName(String mLastName) {
this.mLastName = mLastName;
}
/**
* @return the mFuelLevel
*/
public int getmFuelLevel() {
return mFuelLevel;
}
/**
* @param mFuelLevel the mFuelLevel to set
*/
public void setmFuelLevel(int mFuelLevel) {
this.mFuelLevel = mFuelLevel;
}
/**
* @return the mDamage
*/
public int getmDamage() {
return mDamage;
}
/**
* @param mDamage the mDamage to set
*/
public void setmDamage(int mDamage) {
this.mDamage = mDamage;
}
/**

* @return the mPosicion


*/
public Vector3D getmPosicion() {
return mPosicion;
}
/**
* @param mPosicion the mPosicion to set
*/
public void setmPosicion(Vector3D mPosicion) {
this.mPosicion = mPosicion;
}
/**
* @return the mVelocity
*/
public Vector3D getmVelocity() {
return mVelocity;
}
/**
* @param mVelocity the mVelocity to set
*/
public void setmVelocity(Vector3D mVelocity) {
this.mVelocity = mVelocity;
}
public SpaceShip()
{
mFirstName = "DefaultFirstName";
mLastName = "DefaultLastName";
mFuelLevel = 0;
mDamage = 0;
mPosicion = new Vector3D(0.0f, 0.0f, 0.0f);
mVelocity = new Vector3D(1.0f, 1.0f, 1.0f);
}
public SpaceShip(String firstName, String lastName,
int fuelLevel, int damage,
Vector3D pos, Vector3D vel)
{
mFirstName = firstName;
mLastName = lastName;
mFuelLevel = fuelLevel;
mDamage = damage;
mPosicion = pos;
mVelocity = vel;
}
public String toString()
{
return(mFirstName + " " + mLastName);
}
public void Fly()
{
System.out.printf("Nave volando...\n");
}

public void Attack()


{
System.out.printf("Nave atacando...\n");
}
public void Draw()
{
System.out.printf("Nave dibujndose...\n");
}
public void ReadData()
{
String sData = "";
try
{
System.out.printf("Ingrese el nombre: ");
InputStreamReader isr = new
InputStreamReader(System.in);
BufferedReader streamInput = new BufferedReader(isr);
sData = streamInput.readLine();
mFirstName = sData;
}
catch(IOException e)
{
System.err.println("Error: " + e.getMessage());
}
try
{
System.out.printf("Ingrese el nivel de combustible: ");
InputStreamReader isr = new
InputStreamReader(System.in);
BufferedReader streamInput = new BufferedReader(isr);
sData = streamInput.readLine();
mFuelLevel = Integer.parseInt(sData);
}
catch(IOException e)
{
System.err.println("Error: " + e.getMessage());
}
}
public void PrintStatistics()
{
System.out.printf("==========================");
System.out.printf("Capitn de la Nave: %s\n", toString());
System.out.printf("Nivel de combustible: %d\n",
mFuelLevel);
System.out.printf("Nivel de escudo: %d", mDamage);
System.out.printf("Posicin de la Nave: <%f, %f, %f>\n",
mPosicion.getX(),
mPosicion.getY(),
mPosicion.getZ());
System.out.printf("Velocidad de la Nave: <%f, %f, %f>\n",
mVelocity.getX(),

mVelocity.getY(),
mVelocity.getZ());
}
}

Class Program
package javaappspaceshipsgame;
/**
* @author CV & MZ
*/
public class Program
{
private static SpaceShip[] ArraySS = new SpaceShip[2];
//private static SpaceShip ObjSS1;
//private static SpaceShip ObjSS2;
public static void main(String[] args)
{
Initialize();
Print();
}
public static void Initialize()
{
/*
ObjSS1 = new SpaceShip("Cesar", "Villacis", 90, 0, new
Vector3D(5.0f, 6.0f, -3.0f),
new Vector3D(1.0f, 1.0f, 0.0f));
ObjSS2 = new SpaceShip("Margarita", "Zambrano", 90, 0, new
Vector3D(5.0f, 6.0f, -3.0f),
new Vector3D(1.0f, 1.0f, 0.0f));
*/
ArraySS[0] = new SpaceShip("Cesar", "Villacis", 90, 0, new
Vector3D(5.0f, 6.0f, -3.0f),
new Vector3D(1.0f, 1.0f, 0.0f));
ArraySS[1] = new SpaceShip("Margarita", "Zambrano", 90, 0,
new Vector3D(5.0f, 6.0f, -3.0f),
new Vector3D(1.0f, 1.0f, 0.0f));
}
public static void Print()
{
/*
ObjSS1.Draw();
ObjSS1.Fly();
ObjSS1.Attack();
ObjSS1.PrintStatistics();
System.out.printf("\n");
ObjSS2.Draw();
ObjSS2.Fly();
ObjSS2.Attack();
ObjSS2.PrintStatistics();
System.out.printf("\n");
*/

ArraySS[0].Draw();
ArraySS[0].Fly();
ArraySS[0].Attack();
ArraySS[0].PrintStatistics();
System.out.printf("\n");
ArraySS[1].Draw();
ArraySS[1].Fly();
ArraySS[1].Attack();
ArraySS[1].PrintStatistics();
System.out.printf("\n");
}
}

CAPTURAS DE PANTALLA

CIRCUITO COMPLEJO
/*
* To change this license header, choose License Headers in Project
Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jappconsolecomplexcircuit;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
*
* @author DavidAndres
*/
public class Complex {
private double mReal;
private double mImag;

public Complex(){
mReal = 0.0; mImag = 0.0;
}
public Complex(double a, double b){
mReal = a;
mImag = b;
}
public Complex(Complex C){

mReal = C.mReal;
mImag = C.mImag;
}

public void Read(){


String sData=" ";
try
{
System.out.printf("Ingrese el valor real: ");
InputStreamReader isr= new InputStreamReader(System.in);
BufferedReader streamReader= new BufferedReader(isr);
sData= streamReader.readLine();

setReal(Double.parseDouble(sData));
}
catch(IOException e)
{
System.err.println("Error: " +e.getMessage());
}
try
{
System.out.printf("Ingrese el valor imaginario: ");
InputStreamReader isr= new InputStreamReader(System.in);
BufferedReader streamReader= new BufferedReader(isr);
sData= streamReader.readLine();

setImag(Double.parseDouble(sData));
}

catch(IOException e)
{
System.err.println("Error: " +e.getMessage());
}
}
public Complex Addition(Complex A, Complex B){
Complex temp = new Complex();
temp.setReal(A.getReal() + B.getReal());
temp.setImag(A.getImag() + B.getImag());

return(temp);
}
public Complex Subtraction(Complex A, Complex B){
Complex temp = new Complex();
temp.setReal(A.getReal() - B.getReal());
temp.setImag(A.getImag() - B.getImag());

return(temp);
}
public Complex Product(Complex A, Complex B){
Complex temp = new Complex();
temp.setReal((A.getReal() * B.getReal()) - (A.getImag() * B.getImag()));
temp.setImag((A.getReal() * B.getImag()) + (A.getImag() *
B.getReal()));

return(temp);
}
public Complex Division(Complex A, Complex B){
Complex temp = new Complex();

temp.setReal(((A.getReal() * B.getReal()) + (A.getImag() * B.getImag()))


/ ((B.getReal() * B.getReal()) + (B.getImag() * B.getImag()))) ;
temp.setImag(((A.getImag() * B.getReal()) - (A.getReal() * B.getImag()))
/ ((B.getReal() * B.getReal()) + (B.getImag() * B.getImag())));

return(temp);
}
public double Magnitude(Complex A ){
double temp = 0.0;
temp = Math.sqrt((A.getReal()*A.getReal())+
(A.getImag()*A.getImag()));
return(temp);
}
public double Angle(Complex A ){
double temp = 0.0;
temp = Math.atan(A.getImag()/A.getReal());
return(temp);
}
public void Print() {
if(getImag() >= 0)
System.out.printf(" = %g + %g i \n", getReal(), getImag());
else
System.out.printf(" = %g %g i \n", getReal(), getImag());
}
public void PrintR(double a) {
System.out.printf(" = %g \n",a);
}
public void PrintA(double a) {
System.out.printf(" = %g grados\n",a);
}

/**
* @return the mReal
*/
public double getReal() {
return mReal;
}

/**
* @param mReal the mReal to set
*/
public void setReal(double mReal) {
this.mReal = mReal;
}

/**
* @return the mImag
*/
public double getImag() {
return mImag;
}

/**
* @param mImag the mImag to set
*/
public void setImag(double mImag) {
this.mImag = mImag;
}

} /*
* To change this license header, choose License Headers in Project
Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jappconsolecomplexcircuit;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
*
* @author DavidAndres
*/
public class ComplexCircuit {
private Complex R = new Complex(0.0, 0.0);
private Complex C = new Complex(0.0, 0.0);
private Complex L = new Complex(0.0, 0.0);
private Complex Z = new Complex(0.0, 0.0);
private double f = 0.0;
private double z = 0.0;
private double fp = 0.0;

public ComplexCircuit()
{
R = new Complex(0.0, 0.0);

C = new Complex(0.0, 0.0);


L = new Complex(0.0, 0.0);
Z = new Complex(0.0, 0.0);
f = 0.0;
z = 0.0;
fp = 0.0;
}

public void Read()


{
String sData=" ";

try
{
System.out.printf("Ingrese el valor de la Frecuencia F: ");
InputStreamReader isr= new InputStreamReader(System.in);
BufferedReader streamReader= new BufferedReader(isr);
sData= streamReader.readLine();

f = Double.parseDouble(sData);
}
catch(IOException e)
{
System.err.println("Error: " +e.getMessage());
}

try
{

System.out.printf("Ingrese el valor de la Resistencia R: ");


InputStreamReader isr= new InputStreamReader(System.in);
BufferedReader streamReader= new BufferedReader(isr);
sData= streamReader.readLine();

R.setReal(Double.parseDouble(sData));
R.setImag(0.0);
}
catch(IOException e)
{
System.err.println("Error: " +e.getMessage());
}

try
{
System.out.printf("Ingrese el valor de la Capacitancia C: ");
InputStreamReader isr= new InputStreamReader(System.in);
BufferedReader streamReader= new BufferedReader(isr);
sData= streamReader.readLine();

C.setImag(Double.parseDouble(sData));
C.setReal(0.0);
}
catch(IOException e)
{
System.err.println("Error: " +e.getMessage());
}

try
{
System.out.printf("Ingrese el valor de la Inductancia L: ");
InputStreamReader isr= new InputStreamReader(System.in);
BufferedReader streamReader= new BufferedReader(isr);
sData= streamReader.readLine();

L.setImag(Double.parseDouble(sData));
L.setReal(0.0);
}
catch(IOException e)
{
System.err.println("Error: " +e.getMessage());
}
}

public void ComplexInductance()


{
L.setImag(2.0 * Math.PI * f * L.getImag());
L.setReal(0.0);
}

public void ComplexCapacitance()


{
C.setImag(1.0 / (2.0 * Math.PI * f * C.getImag()));
C.setReal(0.0);
}

public void ComplexImpedance()


{
Z = Z.Addition(R, Z.Subtraction(L, C));
z = Z.Magnitude(Z);
}

public void PowerFactor()


{
fp = Z.Magnitude(Z.Division(R, Z));
}

public void Print()


{
System.out.printf("Impedancia ");
Z.PrintR(z);
System.out.printf("Factor de potencia ");
Z.PrintR(fp);
}
} /*
* To change this license header, choose License Headers in Project
Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jappconsolecomplexcircuit;

/**
*
* @author DavidAndres

*/
public class Program {

private static ComplexCircuit ObjCC = new ComplexCircuit();

public static void main(String[] args)


{
Read();
Calculate();
Print();
}

public static void Read()


{
ObjCC.Read();
}

public static void Calculate()


{
ObjCC.ComplexCapacitance();
ObjCC.ComplexInductance();
ObjCC.ComplexImpedance();
ObjCC.PowerFactor();
}

public static void Print()


{
ObjCC.Print();

}
CAPTURAS DE PANTALLA

También podría gustarte