PDA

Ver la versión completa : Problema Programacion Java



Arkanimus
05-11-2010, 23:04
Estoy haciendo un programa con GUI el cual realiza operaciones sobre un archivo .txt algo asi como

proceso1 #23
proceso2 #44
proceso3 #21
proceso4 #88

y tengo que calcular la media de esos valores, en un post de este foro (http://www.hackhispano.com/foro/showthread.php?t=33225) encontre algo parecido y trate de implementarlo en mi codigo pero no me dio resultado, este es mi codigo en NetBeans Lector.java:

package lector;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JFileChooser;
import java.util.ArrayList;

/**
*
* @author Administrador
*/
public class LectorGUI extends javax.swing.JFrame {




/**
*
* @author djagus
*/
public class TxTFilter extends javax.swing.filechooser.FileFilter{
final static String txt= "txt";
/** Creates a new instance of XMLFilter */
public TxTFilter() {
}



public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String s = f.getName();
int i = s.lastIndexOf('.');

if (i > 0 && i < s.length() - 1) {
String extension = s.substring(i+1).toLowerCase();
if (txt.equals(extension)) {
return true;
} else {
return false;
}
}
return false;
}

public String getDescription() {
return "Archivos .txt";
}

}

/** Creates new form LectorGUI */
public LectorGUI() {
initComponents();
}

public static double media(Object arr[ ]) numbers)
{

double sum = 0.0;

for(int i = 0; i < arr.length ; i++)
{
sum += ((Double)arr[i]).doubleValue(); //Usas este método de la clase Double para obtener el valor encapsulado por el objeto de tipo Double. Para ello es necesario hacer un casting a (Double) ya que con esto indicas que un Objeto cualquiera va a ser tratado como un Double.
}

return sum / arr.length;
}

public static double varianza(Object arr[ ], double media) //Lo mismo con esta función
{
double sum = 0.0;

for(int i = 0; i < arr.length ; i++)
{
sum += Math.pow((((Double)arr[i]).doubleValue()) - media, 2); //idem
}

return sum / (arr.length); // array.length devuelve el número de elementos del array por lo que no es necesario restarle 1.
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();

setDefaultCloseOperation(javax.swing.WindowConstan ts.EXIT_ON_CLOSE);

jButton1.setText("Imprimir Texto");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});

jButton2.setText("Exit");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});

jLabel1.setText("Pegue su archivo de texto en la ruta C://");

jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.Grou pLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax. swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax. swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(120, 120, 120)
.addComponent(jButton2))
.addComponent(jLabel1)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 351, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(242, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.Grou pLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(25, 25, 25)
.addGroup(jPanel1Layout.createParallelGroup(javax. swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addGap(33, 33, 33)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(347, Short.MAX_VALUE))
);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(98, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);

pack();
}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

JFileChooser chooser = new JFileChooser();
chooser.setApproveButtonText("Abrir .txt");
chooser.addChoosableFileFilter(new TxTFilter());
chooser.showOpenDialog(null);
File archivo=chooser.getSelectedFile();
try {
ArrayList lista = new ArrayList();
BufferedReader reader = new BufferedReader(new FileReader(archivo));

boolean eof = false;
while (!eof) {
String linea = reader.readLine();
if (linea == null) eof = true;
else{
linea = linea.split("#")[0];
Double d = new Double(Double.parseDouble(linea)); //Creas un objeto de tipo Double, que contiene el número indicado en el fichero "read.txt"
lista.add(d); //y lo añades a la lista




}
}
reader.close();
} catch (Exception ex) {
System.out.println("Error -- " +ex.toString());
}
Object numbers[] =lista.toArray();


System.out.println("\n Resultados \n");

double aux_media = media(numbers);
System.out.println(" media : " + aux_media);

double aux_var = varianza(numbers,aux_media);
System.out.println(" varianza : " + aux_var);
System.out.println(" desv. estandar : " + Math.sqrt(aux_var));
}


// TODO add your handling code here:
}





private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0); // TODO add your handling code here:
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LectorGUI().setVisible(true);
}
});
}

// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration



}


este es el main:


package lector;

/**
*
* @author Administrador
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {

new LectorGUI().setVisible(true);
}

}



Porfavor ruego que alguien me ayude a resolver este problema me imagino que el error se debe al orden del codigo.

Saludos y muchas gracias

hystd
06-11-2010, 03:41
Para empezar...


linea = linea.split("#")[0];

Revisa eso. Según la documentación de Java, el método split hace lo siguiente:


split

public String[] split(String regex)

Splits this string around matches of the given regular expression.

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

The string "boo:and:foo", for example, yields the following results with these expressions:

Regex Result
: { "boo", "and", "foo" }
o { "b", "", ":and:f" }

Parameters:
regex - the delimiting regular expression
Returns:
the array of strings computed by splitting this string around matches of the given regular expression
Throws:
PatternSyntaxException - if the regular expression's syntax is invalid
Since:
1.4
See Also:
Pattern



Por lo que en tu caso, teniendo la entrada:

proceso1 #23
proceso2 #44
proceso3 #21
proceso4 #88

Al acceder al elemento [0] devuelto por el método split, tendrás una lista con los siguientes datos: "proceso1", "proceso2", "proceso3",... Y eso te va a dar error cuando hagas una conversión a double.

La solución a esto es sustituir esa línea por:


linea = linea.split("#")[1];

Y de esta forma tendrás la lista con los datos correctos: "23", "44", "21", "88".

Un saludo.

Arkanimus
06-11-2010, 18:12
Gracias por tu ayuda me sirvio de mucho.. corregi los detalles errores de parentesis etc.. pero ahora al calcular la varianza y la desviacion estandar el programa me imprime 0.0 no me lo esta calculando aqui esta el codigo, como hago para que me la calcule ??:

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

/*
* LectorGUI.java
*
* Created on 25-oct-2010, 9:04:19
*/

package lector;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JFileChooser;

/**
*
* @author Administrador
*/
public class LectorGUI extends javax.swing.JFrame {








public class TxTFilter extends javax.swing.filechooser.FileFilter{
final static String txt= "txt";
/** Creates a new instance of XMLFilter */
public TxTFilter() {
}

public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String s = f.getName();
int i = s.lastIndexOf('.');

if (i > 0 && i < s.length() - 1) {
String extension = s.substring(i+1).toLowerCase();
if (txt.equals(extension)) {
return true;
} else {
return false;
}
}
return false;
}

public String getDescription() {
return "Archivos .txt";
}

}

/** Creates new form LectorGUI */
public LectorGUI() {
initComponents();
}

public static double media(Object arr[ ])
{

double sum = 0.0;

for(int i = 0; i < arr.length ; i++)
{
sum += ((Double)arr[i]).doubleValue(); //Usas este método de la clase Double para obtener el valor encapsulado por el objeto de tipo Double. Para ello es necesario hacer un casting a (Double) ya que con esto indicas que un Objeto cualquiera va a ser tratado como un Double.
}

return sum / arr.length;
}

public static double varianza(Object arr[ ], double media) //Lo mismo con esta función
{
double sum = 0.0;

for(int i = 0; i < arr.length ; i++)
{
sum += Math.pow((((Double)arr[i]).doubleValue()) - media, 2); //idem
}

return sum / (arr.length); // array.length devuelve el número de elementos del array por lo que no es necesario restarle 1.
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();

setDefaultCloseOperation(javax.swing.WindowConstan ts.EXIT_ON_CLOSE);

jButton1.setText("Imprimir Texto");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});

jButton2.setText("Exit");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});

jLabel1.setText("Pegue su archivo de texto en la ruta C://");

jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.Grou pLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax. swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax. swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(120, 120, 120)
.addComponent(jButton2))
.addComponent(jLabel1)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 351, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(242, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.Grou pLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(25, 25, 25)
.addGroup(jPanel1Layout.createParallelGroup(javax. swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addGap(33, 33, 33)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(347, Short.MAX_VALUE))
);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(98, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);

pack();
}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

JFileChooser chooser = new JFileChooser();
chooser.setApproveButtonText("Abrir .txt");
chooser.addChoosableFileFilter(new TxTFilter());
chooser.showOpenDialog(null);
File archivo=chooser.getSelectedFile();
ArrayList lista = new ArrayList();
try {
BufferedReader reader = new BufferedReader(new FileReader(archivo));

boolean eof = false;
while (!eof) {
String linea = reader.readLine();
if (linea == null) eof = true;
else{
linea = linea.split("#")[1];

Double d = new Double(Double.parseDouble(linea)); //Creas un objeto de tipo Double, que contiene el número indicado en el fichero "read.txt"
lista.add(d); //y lo añades a la lista
}
}
reader.close();

}
catch (Exception ex) {
System.out.println("Error -- " +ex.toString());
}

Object numbers[] =lista.toArray();


System.out.println("\n Resultados \n");

double aux_media = media(numbers);
System.out.println(" media : " + aux_media);

double aux_var = varianza(numbers,aux_media);
jTextArea1.append(" varianza : " + aux_var);
jTextArea1.append(" desv. estandar : " + Math.sqrt(aux_var));





// TODO add your handling code here:
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0); // TODO add your handling code here:
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LectorGUI().setVisible(true);
}
});
}

// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration



}








Muchas gracuas un abrazo

Arkanimus
06-11-2010, 18:40
ya lo solucione era por que habia un espacio entre procesos en el archivo .txt

ahora tengo que hacer que la moda, varianza y desviacion estandar sean imprimidas en un archivo html :S alguien sabe como hacer eso?

saludos y abrazos

hckr
06-11-2010, 19:23
Creo que será un poco mas complicado que en un archivo de texto porque tienes que decirle al programa (no le hables al compilador, que te veo venir) que los saltos de líneas van con <b>, que las negritas con <b>...etc

Arkanimus
06-11-2010, 19:49
Creo que será un poco mas complicado que en un archivo de texto porque tienes que decirle al programa (no le hables al compilador, que te veo venir) que los saltos de líneas van con <b>, que las negritas con <b>...etc

pero se me ocurre que genere en vez de un archivo html un .txt y que java le cambie la extension..

hystd
06-11-2010, 21:21
pero se me ocurre que genere en vez de un archivo html un .txt y que java le cambie la extension..

Muy bien si señor!!! Da gusto ver el trabajo bien hecho...

No sé por qué tengo la sensación, tal vez esté equivocado, que has ido haciendo tu programa a base de cut&paste de código que te has ido encontrando por ahí, sin ni siquiera saber qué, cómo y por qué se está haciendo en esas líneas. Es por ello que te está pasando lo que te está pasando y dices la genialidad que acabas de decir de simplemente cambiar la extensión.

Pregunto yo... si vas a hacer esa genialidad, ¿para qué quieres pasarlo a html? ¿No es más fácil dejarlo como está, en un .txt y que el navegador muestre ese fichero texto plano con el mimetype="text/plain" de toda la vida?

Un saludo.