Sunday, July 24, 2005

Mejoras al lenguaje DUDU+

He mejorado el leguaje dudu+ ya que tenia algunos bugs.
Tambien muestro el resultado de un arbol del diagrama del test.java al cual se muestra a continuación:

C:\Documents and Settings\vns\Escritorio\MiniJava>java dudu test.java
Start parsing...
Start
Class
Field
Literal
Field
Array
Literal
Field
MakeStack
Statement
Identifier: var
Assignment
Suma
Identifier: var
Literal
Statement
Multi
Identifier: Stack
Identifier: var
Statement
Identifier: Stack
Statement
Repeat
Statement
Identifier: var
Assignment
Suma
Identifier: var
Literal
Relational
Identifier: var
Literal
Class
Field
Literal
Field
Array
Literal
Field
MakeStack
Statement
Identifier: varible
Assignment
Suma
Identifier: variable
Literal
Statement
Multi
Identifier: Stack
Identifier: variable
Statement
Identifier: Stack
Statement
Repeat
Statement
Identifier: varible
Assignment
Suma
Identifier: variable
Literal
Relational
Identifier: variable
Literal
DuDu Tree successfully end.

Friday, July 22, 2005

Calculadora

package estructura.projecto.Calculadura;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;

public class Calculadura extends WindowAdapter implements ActionListener
{
int a=0,b=0;
JFrame ventana;
String operacion="";
JTextField texto;
JButton digitos[]=new JButton[10];
JButton operadores[]=new JButton[4];

JButton botAC;
JButton guardar;
JButton leer;

JPanel pDigitos;

Calculadura()
{
botAC=new JButton("AC");
guardar=new JButton("Str");
leer=new JButton("Rd");

ventana=new JFrame("Calculadura v1.0 by Dudu TEAM");
texto=new JTextField();
pDigitos=new JPanel();
pDigitos.setLayout(new GridLayout(4,4));

//instanciando digitos
for (int i=0;i<10;i++) i="0;i<10;i++)" i="0;i<4;i++)" i="0;i<10;i++)" i="0;i<4;i++)" mario="new" i="0;i<3;i++)" operacion="e.getActionCommand();" a="Integer.parseInt(texto.getText());" b="Integer.parseInt(texto.getText());" archivo="new" man="new" archivo="new" man="new" a="b="0;" asd="new">

Editor Dudush


package estructura.projecto.Editor;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextArea;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class Dudush
{
private final JScrollPane scroll;
private int letras = 0;
private final JFrame ventana;
private final JLabel estado;
private JPanel panel;
private final JTextArea texto;

public Dudush()
{
ventana = new JFrame("Dudush v.0.1. Editor oficial de Dudu ++");
estado = new JLabel("estado");
panel = new JPanel();
texto = new JTextArea();
scroll = new JScrollPane(texto);

texto.addKeyListener( new KeyListener()
{

public void keyPressed(KeyEvent e)
{
if ( e.getKeyCode()==127 || e.getKeyCode()==8)
{
if (letras>0) letras--;
}
else
{
if ( (!(e.getKeyCode()>=37 &&amp; e.getKeyCode()<=40)) && e.getKeyCode()!=10 )letras++; } estado.setText("letras: "+letras); System.out.println("key ->"+e.getKeyCode() );
}

public void keyReleased(KeyEvent e)
{

}

public void keyTyped(KeyEvent e)
{

}

}

);

panel.setLayout (new BorderLayout());
panel.add(texto,BorderLayout.NORTH);
panel.add(estado,BorderLayout.SOUTH);

ventana.setLayout(new GridLayout(2,1));
ventana.getContentPane().add(texto);
ventana.add(estado);
ventana.setSize(500,300);


//Create the menu bar.
JMenuBar menuBar = new JMenuBar();
ventana.setJMenuBar(menuBar);

//Build the first menu.
JMenu mnuArchivo = new JMenu("Archivo");
menuBar.add(mnuArchivo);

JMenuItem abrir = new JMenuItem("Abrir");

abrir.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("abrir");

JFileChooser fc = new JFileChooser();
int retorno = fc.showOpenDialog(ventana);
fc.setVisible(true);

if(retorno == JFileChooser.APPROVE_OPTION) {

String nombre = fc.getSelectedFile().getName();

String path = fc.getSelectedFile().getAbsolutePath();

System.out.println(nombre+" "+path);

try
{
FileInputStream fi = new FileInputStream(path);
boolean done=false;
while (!done)
{
int buff=fi.read();
//System.out.println("ss"+buff);
if (buff==-1) done=true;
else texto.setText(texto.getText()+String.valueOf((char)buff));

}

}
catch(Exception ex)
{
ex.printStackTrace();

}
}
}
});

JMenuItem guardar = new JMenuItem("Guardar");

guardar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Guardar");

JFileChooser fc = new JFileChooser();
int retorno = fc.showOpenDialog(ventana);
fc.setVisible(true);

if(retorno == JFileChooser.APPROVE_OPTION) {

String nombre=fc.getSelectedFile().getName();

String path=fc.getSelectedFile().getAbsolutePath();

System.out.println(nombre+" "+path);

try{
FileWriter impri = new FileWriter((path),false);
impri.append(texto.getText());
impri.close();
}
catch(Exception ex)
{
ex.printStackTrace();

}
}
}
});

JMenuItem imprimir = new JMenuItem("Imprimir");
imprimir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("imprimir");

try{
FileWriter impri = new FileWriter("c:\\temp",false);
impri.append(texto.getText());
impri.close();
Process proc = Runtime.getRuntime().exec("cmd /C type c:\\temp>LPT1");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});

JMenuItem salir=new JMenuItem("Salir");

salir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});

mnuArchivo.add(abrir);
mnuArchivo.add(guardar);
mnuArchivo.add(imprimir);
mnuArchivo.add(salir);

ventana.setExtendedState(ventana.getExtendedState() | JFrame.MAXIMIZED_BOTH);

ventana.setVisible(true);

ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

/*ventana.setState(JFrame.NORMAL);
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimension = toolkit.getScreenSize();
ventana.setSize(dimension);
*/
}

public static void main(String args[])
{
Dudush editor=new Dudush();
}
}

Monday, July 11, 2005

test.java

Este es el archivo para comprobar el lenguaje DUDU+

//test.java
// definicion clase
class test{
//declaracion variables
public int var = 0;
public int[] matriz = new int[0];
public int Stack = make stack;

var = var + 1;

//uso del stack
Stack.addStack( var );
Stack.ordStack( ascendente );

//REPEAT... UNTIL
repeat

var = var + 1;

until ( var > 0)

}

class test1{
//declaracion variables
public int var = 0;
public int[] matriz = new int[0];
public int Stack = make stack;

varible = variable + 1;

//uso del stack
Stack.addStack( variable );
Stack.ordStack( ascendente );

//REPEAT... UNTIL
repeat

varible = variable + 1;

until ( variable > 0)

}

Monday, June 27, 2005

A) Explique el siguiente error:

char c = "A"; /* define and inicialize c */

La variable c es un char por lo tanto se le asigna con 'A' y no con "A".

D) Lee un archivo que contenga los datos de un estudiante

/*
* Created on 06/25/2005
*
* Lee un archivo que contenga los datos de un estudiante,
* nombre(1-25), apellido(26-50), telefono(51-62), matricula(63-72)
* y que permita ordenar y buscar por un registro en particular
*/
package estructura.examen;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.Vector;

/**
* @author vns
*
*/
public class ArchivoEst {

private LinkedList datalist;

/**
*
*/
public ArchivoEst() {
super();
}

/**
* @param dataArray
*/
public ArchivoEst(LinkedList data) {
this.datalist = data;
}

/**
* @return Returns the datalist.
*/
public LinkedList getDatalist() {
return datalist;
}
/**
* @param datalist The datalist to set.
*/
public void setDatalist(LinkedList datalist) {
this.datalist = datalist;
}

/**
* Devuelve null en caso de error en la lectura
*
* @param string
* @return ArchivoEst
*/
public static ArchivoEst ReadFile(String file) {
BufferedReader fin = null;
LinkedList data = new LinkedList();
String line = null;
ArchivoEst archivo = null;

try {
fin = new BufferedReader( new FileReader(file) );

while ( (line = fin.readLine()) != null)
data.insertAtBack( new Estudiante(
line.substring(0,24),line.substring(25,49),
line.substring(50,61),line.substring(62,71) )
);
archivo = new ArchivoEst(data);
} catch (FileNotFoundException e) {
System.err.println("Archivo no encontrado");
e.printStackTrace();

} catch (IOException e) {
System.err.println("Error en la lectura");
e.printStackTrace();

} catch (Exception e) {
System.err.println("Error general");
e.printStackTrace();

}finally{
try {
fin.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return archivo;
}

/**
* @param sample
* @param Field
*/
public void sort(Object sample, String Field) {
datalist.sort(sample, Field);
}

/**
* @param field
* @return
*/
public Object[] find(String field) {
return datalist.find(field);
}
/**
* @return
*/
public boolean isEmpty() {
return datalist.isEmpty();
}

/**
*
*/
public void print() {
Nodo nodo = datalist.getFirst();

if (!datalist.isEmpty())
while (nodo != null){
((Estudiante)nodo.getData()).toString();

nodo = nodo.getNext();
}
}

}
class Estudiante {
private String nombre;
private String apellido;
private int telefono;
private int matricula;

/**
*
*/
public Estudiante() {
}


/**
* @param nombre
* @param apellido
* @param telefono
* @param matricula
*/
public Estudiante(String nombre, String apellido, String telefono,
String matricula) {
super();
this.nombre = nombre;
this.apellido = apellido;
this.telefono = Integer.parseInt(telefono);
this.matricula = Integer.parseInt(matricula);
}

/**
* @return Returns the apellido.
*/
public String getApellido() {
return apellido;
}
/**
* @param apellido The apellido to set.
*/
public void setApellido(String apellido) {
this.apellido = apellido;
}
/**
* @return Returns the matricula.
*/
public int getMatricula() {
return matricula;
}
/**
* @param matricula The matricula to set.
*/
public void setMatricula(int matricula) {
this.matricula = matricula;
}
/**
* @return Returns the nombre.
*/
public String getNombre() {
return nombre;
}
/**
* @param nombre The nombre to set.
*/
public void setNombre(String nombre) {
this.nombre = nombre;
}
/**
* @return Returns the telefono.
*/
public int getTelefono() {
return telefono;
}
/**
* @param telefono The telefono to set.
*/
public void setTelefono(int telefono) {
this.telefono = telefono;
}
/*
* Display the persona
*/
public String toString() {

return nombre + " " + apellido + " " + telefono + " " + matricula;
}

}
class Nodo{

private Object data;
private Nodo next;

/**
* @param object
*/
public Nodo(Object object) {
this(object, null);
}

/**
* @param data
* @param next
*/
public Nodo(Object data, Nodo next) {
super();
this.data = data;
this.next = next;
}

/**
* @return Returns the data.
*/
public Object getData() {
return data;
}
/**
* @param data The data to set.
*/
public void setData(Object data) {
this.data = data;
}
/**
* @return Returns the next.
*/
public Nodo getNext() {
return next;
}
/**
* @param next The next to set.
*/
public void setNext(Nodo next) {
this.next = next;
}
}
class LinkedList{
private Nodo head = null;
private Nodo tail = null;

public boolean isEmpty(){
return head == null;
}

public Nodo getFirst() {
return head;
}

public void insertAtFront(Object nodo){
if ( isEmpty() ) {
head = tail = new Nodo(nodo, null);
} else {
head = new Nodo(nodo, head);
}
}

public void insertAtBack(Object nodo){
if ( isEmpty() ) {
head = tail = new Nodo(nodo, null);
} else {
tail.setNext( new Nodo(nodo, null) );
tail = tail.getNext();
}
}

//Ordena por un campo especifico
public void sort(Object sample, String field){
FieldComparator fc = new FieldComparator(sample, field);
Nodo nodo = head;

if (isEmpty()) {
return;
}

if (fc.isValid())
while ( nodo != null ) {
if ( ( fc.compare(nodo, nodo.getNext()) ) <= -1 ) {
swap(nodo, nodo.getNext());
}

nodo = nodo.getNext();
}

}

/**
* @param nodo
* @param next
*/
private void swap(Nodo nodo, Nodo next) {
Object temp = nodo.getData();
nodo.setData(next.getData());
next.setData(temp);
}

//Busca segun un campo especifico
/**
*
* @return Object[]. Return null when is empty or is no valid the field
*/
public Object[] find(String field){
Object[] objects = null;
Nodo nodo = head;
FieldComparator fc = new FieldComparator(new Estudiante(), field);
int i = 0;

if (isEmpty()) {
return null;
}

if( fc.isValid() )
while ( nodo != null ) {

if ( (fc.compare(nodo, field) ) == 0 ) {
objects[i] = nodo.getData();
}
i++;
nodo = nodo.getNext();
}

return objects;
}

/*
*
*/
public void print() {
// TODO Auto-generated method stub
}
}

class FieldComparator implements Comparator{

private Class c;
private Field[] fields;
private Vector fieldVec;
private String sortBy;
boolean fieldMatch = true;

/**
*
*/
public FieldComparator() {
super();
}
/**
* @param sample
* @param field
*/
public FieldComparator(Object sample, String field) {
this.c = sample.getClass();
this.sortBy = field;
fieldVec = new Vector();
fields = c.getFields();

for (int i = 0; i < fields.length; i++) {
fieldVec.add( fields[i].getName() );
}

fieldMatch = fieldVec.contains( getSortBy() );
}

/**
* @return Returns the sortBy.
*/
public String getSortBy() {
return sortBy;
}
/**
* @param sortBy The sortBy to set.
*/
public void setSortBy(String sortBy) {
this.sortBy = sortBy;
}

public boolean isValid(){
return fieldMatch;
}

/**
* You should set the field to compared, set SortBY or in the constructor
*
* @param the objects to compared, arg0 and arg1
*
* @return the value 0 if the argument Object is equal to this Object;
* a value less than 0 if this Object is lexicographically less than the Object argument;
* and a value greater than 0 if this Object is lexicographically greater than the Object argument.
*/
public int compare(Object arg0, Object arg1) {
String field0 = getfield(arg0, getSortBy() );
String field1 = getfield(arg1, getSortBy() );

return field0.compareTo( field1 );
}

public int compare(Object arg0, String field) {
String field0 = getfield(arg0, getSortBy() );

return field0.compareTo( field );
}

/**
* @param arg0
* @param sortBy2
* @return
*/
private String getfield(Object arg0, String sortBy) {
String data = null;

try {

Field field = c.getField( sortBy );
data = (String)field.get( arg0 );

} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
System.err.println("Campo no encontrado");
e.printStackTrace();
} catch (SecurityException e) {
System.err.println("Error en seguridad");
e.printStackTrace();
}

return data;
}

}

Sunday, June 26, 2005

H) Convierte de números Arábicos a Romanos

/*
* Created on 06/25/2005
*
* H) Convierte de números Arábicos a Romanos
*/
package estructura.examen;

/**
* @author vns
*
*/
public class Romanos {

/**
*
*/
public Romanos() {
super();
}

/**
* @param num
* @return
*/
public static String convertirR2A(int num) {
int[] arabicos = {1,4,5,9,10,40,50,90,100,400,500,900,1000};
String[] romanos = {"I","IV","V","IX","X","XL",
"L","XC","C","CD","D","CM","M"};
StringBuffer sb = new StringBuffer();

for(int i = 12; i > = 0 ;i--)
while( num > = arabicos[i] ){
num -= arabicos[i];
sb.append(romanos[i]);
}
return sb.toString();
}

}

Saturday, June 25, 2005

Problemas C, F y G


/*
* Created on 06/25/2005
*
* Esta clase fue probada con JUNIT, usando TDD
* Si desea ver los test, dejar un comentario
*/
package estructura.examen;

/**
* @author vns
*
*/
public class ManejoString {

/**
*
*/
public ManejoString() {
super();
}

/**
* F) Busca un substring en un string dado
*
* @param string
* @param retorno
* @param i
* @param len
*/
public static void subStr(String string, String r, int ind, int len) {
//TODO terminar test
for (int i = ind ; i < ind + len; i++) {
r = r + string.charAt(i);
}
}

/**
* G) Busca la posicion de una Subcadena dentro de otra,
* y si no se encuentra retorna 0
*
* @param string
* @param substring
*/
public static int find(String string, String substring) {
int cont = 0;

//primera manera de hacerlo
/*for (int i = 0; i < string.length(); i++) {
if ( string.charAt(i) == substring.charAt(0) )
for (int j = 0, pos = i; j < substring.length(); j++, pos++){
if ( string.charAt(pos) == substring.charAt(j) ){
cont++;
}else{
cont = 0;
break;
}

if (cont == substring.length()) {
return i;
}
}
}*/

// Segunda manera de hacerlo
for (int j = 0, pos = j; j < string.length(); j++){
if ( string.charAt(j) == substring.charAt(pos) ){
pos++;
cont++;
}else{
pos = 0;
cont = 0;
continue;
}

if ( cont == substring.length()) {
return j - cont + 1;
}
}
return 0;
}

/**
* C) Función length usando for
*
* @param string
* @return
*/
public static int lentghWithFor(String string) {

int i = 0;
for (;;) {
try {
string.charAt(i);
i++;
} catch (StringIndexOutOfBoundsException e) {
return i;
}
}
}

/**
* C) Función length usando While
*
* @param string
* @return
*/
public static int lentghWithWhile(String string) {
int i = 0;
while(true) {
try {
string.charAt(i);
i++;
} catch (StringIndexOutOfBoundsException e) {
return i;
}
}
}

}

Wednesday, June 22, 2005

Problema Estructura

/*
* Created on 06/18/2005
*
* Manejo de estructuras y indices. Dado el ejemplo de una base de datos
*
* a) Los ordena segun el valor de uno de los campos elegidos
* b) Crear un indice para la busqueda a partir de un campo elegido
*/
package estructura;

import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Vector;

/**
* @author vns
*
*/
public class Estructura {

/**
*
*/
public Estructura() {
super();
}

public static void main(String[] args) {

}
}

class Persona {
private String pNombre;
private String pApellido;
private int edad;

/**
* @param nombre
* @param apellido
* @param edad
*/
public Persona(String nombre, String apellido, int edad) {
super();
pNombre = nombre;
pApellido = apellido;
this.edad = edad;
}

/**
*
*/
public Persona() {
}

/**
* @return Returns the pApellido.
*/
public String getPApellido() {
return pApellido;
}

/**
* @param apellido The pApellido to set.
*/
public void setPApellido(String apellido) {
pApellido = apellido;
}

/**
* @return Returns the pNombre.
*/
public String getPNombre() {
return pNombre;
}

/**
* @param nombre The pNombre to set.
*/
public void setPNombre(String nombre) {
pNombre = nombre;
}

/**
* @return Returns the edad.
*/
public int getEdad() {
return edad;
}

/**
* @param edad The edad to set.
*/
public void setEdad(int edad) {
this.edad = edad;
}

/*
* Display the persona
*/
public String print() {

return pNombre + " " + pApellido + " " + edad;
}

}

class HighArrayPersona
{
private Persona[] a;
private int nElems;
LinkedList index = new LinkedList();

public HighArrayPersona(int max)
{
a = new Persona[max];
nElems = 0;
}

public boolean find(String searchKey)
{
int j;
for(j=0; j < nElems; j++)
if(a[j].getPNombre().toString() == searchKey)
break;
if(j == nElems)
return false;
else
return true;
}

public void insert(Persona value)
{
a[nElems] = value;
nElems++;
}

public boolean delete(Persona value)
{
int j;
for(j=0; j < nElems; j++)
if( value == a[j] )
break;
if(j==nElems)
return false;
else
{
for(int k=j; k < nElems; k++)
a[k] = a[k+1];
nElems--;
return true;
}
}

public void display()
{
for(int j=0; j < nElems; j++)
a[j].print();
System.out.println("");
}
//----------------------------------------------------------
// sort elements
public void sort(String field){
Object sample = new Persona();
FieldComparator fieldComparator = new FieldComparator(sample, field);
int i;

for (i = 0; i < nElems; i++)
for (int j = 0; j < nElems; j++)
if ( fieldComparator.compare(a[i],a[j]) <= -1 )
swap(i,j);
}

// create the index for a field
public void createindex(String fields){
for(int i=0; i < nElems; i++)
if ( a[i] != null )
index.add( i, FieldComparator.getField(a[i],fields) ); // add all field of the objects
}

// changes the position i --> j
private void swap(int i, int j){
Persona temp = a[i];
a[i] = a[j];
a[j] = temp;
}

// delete duplicates
public void noDups()
{
int j;
for(j=0; j < nElems; j++) // look for it
for (int i = j; i < nElems; i++)
if( (a[j] == a[i]) && (i != j) && (a[j] != null) && (a[i] != null) )
a[i] = null;

if (j == nElems) // can't find it
return;

for(int k=0; k < nElems; k++){
if ( a[k] == null )
delete(a[k]); // delete all -1 value
}
} // end noDups()
//----------------------------------------------------------

} // end class HighArray

class FieldComparator implements Comparator{

Field[] publicField;
Vector fieldVec;
String SortBY;
boolean nameMatch = true;

/**
*
*/
public FieldComparator() {
super();
}


/**
* @param sample
* @param sortBY
*/
public FieldComparator(Object sample, String sortBY) {
SortBY = sortBY;
Class c = sample.getClass();
fieldVec = new Vector();
//TODO check for SecurityException don't apper
publicField = c.getFields();
for (int i = 0; i < publicField.length; i++) {
fieldVec.add( publicField[i].getName() );
}

nameMatch = fieldVec.contains(sortBY);
}// End constructor


/**
* @return Returns the sortBY.
*/
public String getSortBY() {
return SortBY;
}

/**
* @param sortBY The sortBY to set.
*/
public void setSortBY(String sortBY) {
SortBY = sortBY;
}

/**
* You should set the field to compared, set SortBY or in the constructor
*
* @param the objects to compared, arg0 and arg1
*
* @return the value 0 if the argument Object is equal to this Object;
* a value less than 0 if this Object is lexicographically less than the Object argument;
* and a value greater than 0 if this Object is lexicographically greater than the Object argument.
*/
public int compare(Object arg0, Object arg1) {

String str0 = getField(arg0, getSortBY());
String str1 = getField(arg1, getSortBY());

return str0.compareTo(str1);
}

static public String getField(Object obj, String field){
Class c = obj.getClass();
String string = "";

try {
// TODO check for SecurityException don't apper
Field field0 = c.getField( field );

string = (String)field0.get(obj);

} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return string;
}
}