Autor Tema: Ejemplo extraer datos desde archivo txt con Java FileReader y BufferedReader  (Leído 7947 veces)

josephb401

  • Visitante
quisiera saver si alguien me puede ayudar con este programa no se que pasa me da errores y no se porque.

Código: [Seleccionar]
import java.text.DecimalFormat; //  needed for DecimalFormat class
import java.util.Scanner; // needed for Scanner class
import java.io.*; // needed for file I/O classes

public class Program4
{
public static void main(String[] args) throws IOException
{

// print my name to the screen
System.out.println("Jose A. Pimentel");
System.out.println();

String filename; // to hold the file name
String lineComp; // to hold the name of company
double compNum; // to hold the number of shares
double purchPrice; // to hold the purchase price per shares
double commPurch; // to hold the purchase commission rate
double salesPrice; // to hold the sales price per share
double commSales; // to hold the sales commission



Scanner keyboard = new Scanner(System.in);

//System.out.print("Enter the name of the file: ");
//filename = keyboard.nextLine();

File file = new File("StockData.txt");
Scanner inputFile = new Scanner(file);


while(inputFile.hasNext())
{
// assign every document data to a different variable
lineComp = inputFile.nextLine();
compNum = inputFile.nextDouble();
purchPrice = inputFile.nextDouble();
commPurch = inputFile.nextDouble();
salesPrice = inputFile.nextDouble();
commSales = inputFile.nextDouble();
inputFile.nextLine();

checkValidity(lineComp, compNum, purchPrice, commPurch, salesPrice, commSales);




}

inputFile.close();

}

public static void checkValidity(String company, double numOfShares, double purchPrice,
double commissionP, double salesPrice, double commissionS)
{

/*double compDouble;
double purchDouble;
double commDoubleP;
double salesDouble;
double commDoubleS;*/

DecimalFormat twoDecimals = new DecimalFormat("0.000");

/*compDouble = Double.parseDouble(numOfShares);
purchDouble = Double.parseDouble(purchPrice);
commDoubleP = Double.parseDouble(commissionP);
salesDouble = Double.parseDouble(salesPrice);
commDoubleS = Double.parseDouble(commissionS);*/

double profit;

calcProfit(numOfShares, purchPrice, commissionP, salesPrice, commissionS);

if (numOfShares <= 0)
{

System.out.println(company);
System.out.print("Number of shares invalid: " + twoDecimals.format(numOfShares));

}
if (purchPrice < 0)
{

System.out.println(company);
System.out.print("Purchase price invalid: " + twoDecimals.format(purchPrice));

}
if (salesPrice < 0)
{

System.out.println(company);
System.out.print("Sales price invalid: " + twoDecimals.format(salesPrice));

}
if(commissionP < 0 || commissionP > 0.20)
{

if(commissionS < 0 || commissionS > 0.20)
{

System.out.println(company);
System.out.println("Purchase commission percent ivalid: " + twoDecimals.format(commissionP));
System.out.println(company);
System.out.println("Sales commission percent ivalid: " + twoDecimals.format(commissionS));
}

}

else
{



}


}

public static void calcProfit(double numShares, double priceP, double commP, double priceS, double commS);
{

double commAmountP = 0;
double commAmountS = 0;
double totalP = 0;
double totalS = 0;
double totalAmount = 0;

commAmountP = numShares * priceP * commP;
commAmountS = numShares * priceS * commS;

totalS = numShares * priceS - commAmountS;
totalP = numShares * priceP + commAmountP;

totalAmount = totalS - totalP;

return totalAmount;


}

}
« Última modificación: 23 de Marzo 2015, 08:38 por Alex Rodríguez »

Jorge lopez

  • Sniper
  • Intermedio
  • ***
  • APR2.COM
  • Mensajes: 248
  • @SniperOfElite
    • Ver Perfil
Re:nesesito ayuda urgente!!! java
« Respuesta #1 en: 07 de Marzo 2015, 02:22 »
 Hola  josephb401!

he comentado las lineas de código pertenecientes al método calcProfit que hacen imposible la compilación de tu código.

Son dos errores de sintaxis un tanto básicos, si estas comenzando en java, te recomiendo seguir el curso java desde cero https://www.aprenderaprogramar.com/index.php?option=com_content&view=category&id=68&Itemid=188, donde ademas de poder corregir errores básicos como estos pues aprenderás muchas otras cosas mas.

Aquí tu código con un comentario en cada error:
Código: [Seleccionar]
import java.text.DecimalFormat; //  needed for DecimalFormat class
import java.util.Scanner; // needed for Scanner class
import java.io.*; // needed for file I/O classes

public class Program4
{
public static void main(String[] args) throws IOException
{

// print my name to the screen
System.out.println("Jose A. Pimentel");
System.out.println();

String filename; // to hold the file name
String lineComp; // to hold the name of company
double compNum; // to hold the number of shares
double purchPrice; // to hold the purchase price per shares
double commPurch; // to hold the purchase commission rate
double salesPrice; // to hold the sales price per share
double commSales; // to hold the sales commission



Scanner keyboard = new Scanner(System.in);

//System.out.print("Enter the name of the file: ");
//filename = keyboard.nextLine();

File file = new File("StockData.txt");
Scanner inputFile = new Scanner(file);


while(inputFile.hasNext())
{
// assign every document data to a different variable
lineComp = inputFile.nextLine();
compNum = inputFile.nextDouble();
purchPrice = inputFile.nextDouble();
commPurch = inputFile.nextDouble();
salesPrice = inputFile.nextDouble();
commSales = inputFile.nextDouble();
inputFile.nextLine();

checkValidity(lineComp, compNum, purchPrice, commPurch, salesPrice, commSales);




}

inputFile.close();

}

public static void checkValidity(String company, double numOfShares, double purchPrice,
double commissionP, double salesPrice, double commissionS)
{

/*double compDouble;
double purchDouble;
double commDoubleP;
double salesDouble;
double commDoubleS;*/

DecimalFormat twoDecimals = new DecimalFormat("0.000");

/*compDouble = Double.parseDouble(numOfShares);
purchDouble = Double.parseDouble(purchPrice);
commDoubleP = Double.parseDouble(commissionP);
salesDouble = Double.parseDouble(salesPrice);
commDoubleS = Double.parseDouble(commissionS);*/

double profit;

calcProfit(numOfShares, purchPrice, commissionP, salesPrice, commissionS);

if (numOfShares <= 0)
{

System.out.println(company);
System.out.print("Number of shares invalid: " + twoDecimals.format(numOfShares));

}
if (purchPrice < 0)
{

System.out.println(company);
System.out.print("Purchase price invalid: " + twoDecimals.format(purchPrice));

}
if (salesPrice < 0)
{

System.out.println(company);
System.out.print("Sales price invalid: " + twoDecimals.format(salesPrice));

}
if(commissionP < 0 || commissionP > 0.20)
{

if(commissionS < 0 || commissionS > 0.20)
{

System.out.println(company);
System.out.println("Purchase commission percent ivalid: " + twoDecimals.format(commissionP));
System.out.println(company);
System.out.println("Sales commission percent ivalid: " + twoDecimals.format(commissionS));
}

}

else
{



}


}

public static void calcProfit(double numShares, double priceP, double commP, double priceS, double commS)/*Este punto y coma esta de mas-->****************/;
{

double commAmountP = 0;
double commAmountS = 0;
double totalP = 0;
double totalS = 0;
double totalAmount = 0;

commAmountP = numShares * priceP * commP;
commAmountS = numShares * priceS * commS;

totalS = numShares * priceS - commAmountS;
totalP = numShares * priceP + commAmountP;

totalAmount = totalS - totalP;

return totalAmount;//Un metodo tipo procedimiendo (void) no puede usar la palabra clave "return" (dara error en compilacion)**************************


}

}
Saludos!!
while(estesVivo)
{
  aprende();
  ayuda();
  enseña();
}
if(mueres){teRecordaran();}

toni_apr

  • Avanzado
  • ****
  • Mensajes: 497
  • Curiosidad, es uno de los pilares del Conocimiento
    • Ver Perfil
Re:Mi programa no funciona. ¿Por qué?
« Respuesta #2 en: 07 de Marzo 2015, 14:05 »
Hola joseph

Cuando necesites hacer una consulta, pon un título descriptivo. Ayuda la necesitamos todos, de momento le hemos puesto un título genérico.

Te envío la clase con modificaciones para poder leer el archivo. He eliminado el código que no se utilizaba.
Código: [Seleccionar]
import java.text.DecimalFormat; //  needed for DecimalFormat class
import java.io.*;               // needed for file I/O classes

public class Program4
{
    public static void main(String[] args) throws IOException
    {

        // print my name to the screen
        System.out.println("Jose A. Pimentel");
        System.out.println();
       
        String fileName;    // to hold the file name
        String lineComp;    // to hold the name of company
        double compNum;     // to hold the number of shares
        double purchPrice;  // to hold the purchase price per shares
        double commPurch;   // to hold the purchase commission rate
        double salesPrice;  // to hold the sales price per share
        double commSales;   // to hold the sales commission

        fileName = "C:\\Pruebas\\StockData.txt";

        FileReader inputFile = new FileReader(fileName);
        BufferedReader buferArchivo = new BufferedReader(inputFile);
        String linea = buferArchivo.readLine(); // lee la proxima linea
        while(linea != null)  // minetras haya lineas en el archivo
        {
            if (linea.isEmpty()) { // salta las lineas vacias
                linea = buferArchivo.readLine();
                continue;
            }
            // assign every document data to a different variable
            String separador[] = linea.split(":");
            lineComp = separador[0];
            compNum = Double.parseDouble(separador[1]);
            purchPrice = Double.parseDouble(separador[2]);
            commPurch = Double.parseDouble(separador[3]);
            salesPrice = Double.parseDouble(separador[4]);
            commSales = Double.parseDouble(separador[5]);
           
            checkValidity(lineComp, compNum, purchPrice, commPurch, salesPrice, commSales);
            linea = buferArchivo.readLine();

        }
        buferArchivo.close();
    }
    public static void checkValidity(String company, double numOfShares, double purchPrice,
    double commissionP, double salesPrice, double commissionS)
    {

        DecimalFormat twoDecimals = new DecimalFormat("0.000");

        calcProfit(numOfShares, purchPrice, commissionP, salesPrice, commissionS);

        if (numOfShares <= 0)
        {

            System.out.print(company);
            System.out.println(" Number of shares invalid: " + twoDecimals.format(numOfShares));

        }
        if (purchPrice < 0)
        {

            System.out.print(company);
            System.out.println(" Purchase price invalid: " + twoDecimals.format(purchPrice));

        }
        if (salesPrice < 0)
        {

            System.out.print(company);
            System.out.println(" Sales price invalid: " + twoDecimals.format(salesPrice));

        }
        if(commissionP < 0 || commissionP > 0.20)
        {

            if(commissionS < 0 || commissionS > 0.20)
            {
                System.out.print(company);
                System.out.println(" Purchase commission percent invalid: " + twoDecimals.format(commissionP));
                System.out.print(company);
                System.out.println(" Sales commission percent invalid: " + twoDecimals.format(commissionS));
            }

        }
        else
        {

        }
    }
    public static double calcProfit(double numShares, double priceP, double commP, double priceS, double commS)
    {

        double commAmountP = 0;
        double commAmountS = 0;
        double totalP = 0;
        double totalS = 0;
        double totalAmount = 0;

        commAmountP = numShares * priceP * commP;
        commAmountS = numShares * priceS * commS;

        totalS = numShares * priceS - commAmountS;
        totalP = numShares * priceP + commAmountP;

        totalAmount = totalS - totalP;

        return totalAmount;

    }
}
Envío txt formateado para leer con el programa. Hay que colocar el archivo en la ruta designada.
Código: [Seleccionar]
Mi compañia:1200:1300:1400:150:-99
Tu compañia:1000:800:600:-500:33


Su compañia:1:2:3:4:5
A mi entender parece que sabes lo que quieres conseguir, pero no sabes como perdírselo a Java.
Siendo así, deberías hacer las consultas necesarias en la documentación de Java o seguir uno de nuestros cursos  para poder construir tus programas. Tal como te recomienda el compañero Jorge.

Un apunte: Si colocas todo el código en el main, cuando tu aplicación crezca, será difícil de controlar.

Saludos

 

Sobre la educación, sólo puedo decir que es el tema más importante en el que nosotros, como pueblo, debemos involucrarnos.

Abraham Lincoln (1808-1865) Presidente estadounidense.

aprenderaprogramar.com: Desde 2006 comprometidos con la didáctica y divulgación de la programación

Preguntas y respuestas

¿Cómo establecer o cambiar la imagen asociada (avatar) de usuario?
  1. Inicia sesión con tu nombre de usuario y contraseña.
  2. Pulsa en perfil --> perfil del foro
  3. Elige la imagen personalizada que quieras usar. Puedes escogerla de una galería de imágenes o subirla desde tu ordenador.
  4. En la parte final de la página pulsa el botón "cambiar perfil".