Autor Tema: Ejemplo extraer datos desde archivo txt usando Scanner java y leer números  (Leído 5197 veces)

josephb401

  • Visitante
Hola estoy haciendo este programa y me da un error no se por que me preguntaba si alguien me podia ayudar

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


public class Program6
{
private static Scanner keyboard = new Scanner(System.in);

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


final int MAX_SIZE = 100;

String filename;
int numOfArray;

Fan[] fans = new Fan[MAX_SIZE];


numOfArray = fillArray(fans, MAX_SIZE);

listFanData(fans, numOfArray);
/*
bubbleSortByFan();

bubbleSortByAge();
*/




}

public static int fillArray(Fan[] followers, int max) throws IOException
{
String fileName;
String names = "";
int ages;
int count = 0;
//String[] names = new String[max];
//int[] ages = new int[max];


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

// open the file
File theFile = new File(fileName);

// make sure the file exists
if (!theFile.exists())
System.out.println("File " + fileName + " not found");

else
{
//create a scanner object for to read the file
Scanner inputFile = new Scanner(theFile);


// use a while loop that process the document information
for (count = 0; inputFile.hasNext() || count < followers.length; count++)
{

int i = 1;

if (i*2-1 == count)
{
ages = inputFile.nextInt();
inputFile.nextLine();
followers[count-1] = new Fan(names, ages);

i++;
}

else
names = inputFile.nextLine();

//System.out.println(followers[count].getName());
//System.out.println(followers[count].getAge());





}

System.out.println("There are " + (count / 2) + " fans.");


}

return (count / 2);

}

public static void listFanData(Fan[] follow, int num) throws IOException
{

for (int i = 0; i < num; i++)
{

System.out.println(follow[i].getName());
System.out.println(follow[i].getAge());

}



}

}

AQUI ESTA LA CLASE

Código: [Seleccionar]
import java.io.*;

class Fan
{

private String name;
private int age;



public Fan(String n, int a) throws IOException
{

name = n;
age = a;

}

public String getName()
{

return name;


}

public int getAge()
{

return age;

}

public String toString()
{


return name;

}

}
« Última modificación: 24 de Abril 2015, 20:47 por César Krall »

César Krall

  • Moderador Global
  • Experto
  • *******
  • Mensajes: 2078
  • No vales por lo que dices, sino por lo que haces
    • Ver Perfil
    • aprenderaprogramar.com
Re:Java NESESITO AYUDA URGENTE!!!!!
« Respuesta #1 en: 23 de Abril 2015, 09:12 »
Hola josephb401 por favor lee las indicaciones que se dan en esta url para poner título a los temas: https://www.aprenderaprogramar.com/foros/index.php?topic=1460.0 Cuando crees un tema ponle título como se indica ahí.

Para ejecutar el programa hace falta un archivo de datos ¿tienes el archivo? Adjúntalo como se explica en https://www.aprenderaprogramar.com/foros/index.php?topic=1460.0

Si no tienes el archivo te da el error de que no se encuentra el archivo


Saludos!
Responsable de departamento de producción aprenderaprogramar.com

josephb401

  • Visitante
Re:Java NESESITO AYUDA URGENTE!!!!!
« Respuesta #2 en: 24 de Abril 2015, 04:16 »
hey como estas gracias por responderme aqui te dejo el programo un poquito mas mejorado aunque todavia me da errors tambien te voy a dejar el archivo espero puedas ayudarme

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


public class Program6
{
private static Scanner keyboard = new Scanner(System.in);

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


final int MAX_SIZE = 100;

int numOfArray;

Fan[] fans = new Fan[MAX_SIZE];


numOfArray = fillArray(fans, MAX_SIZE);

listFanData(fans, numOfArray);
/*
bubbleSortByFan();

bubbleSortByAge();
*/




}

public static int fillArray(Fan[] followers, int max) throws IOException
{
String fileName;
//String names = "";
//int ages;
int count = 0;
int i = 1;
int a = 0;
String[] names = new String[max];
int[] ages = new int[max];


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

// open the file
File theFile = new File("FanData.txt");

// make sure the file exists
if (!theFile.exists())
System.out.println("File  + fileName +  not found");

else
{
//create a scanner object for to read the file
Scanner inputFile = new Scanner(theFile);


// use a while loop that process the document information
while (inputFile.hasNext() && count < followers.length)
{



if (i*2-1 == count)
{
ages[a] = inputFile.nextInt();
inputFile.nextLine();

i++;
a++;
}

else
names[a] = inputFile.nextLine();

count++;

}

// close the file
inputFile.close();

for (int j = 0; j <= (count / 2); j++)
{

followers[j] = new Fan(names[j], ages[j]);

}

System.out.println("There are " + (count / 2) + " fans.");




}

return (count / 2);

}

public static void listFanData(Fan[] follow, int num) throws IOException
{

System.out.println("\nList all Mr. Rogeres' fans");

for (int i = 0; i <= num; i++)
{

//System.out.printf("%0s %11d\n ", follow[i].getName(), follow[i].getAge());
System.out.println(follow[i].getName());
System.out.println(follow[i].getAge());



}



}

}


César Krall

  • Moderador Global
  • Experto
  • *******
  • Mensajes: 2078
  • No vales por lo que dices, sino por lo que haces
    • Ver Perfil
    • aprenderaprogramar.com
Hola, con el archivo que has puesto he modificado el código y ahora parece que funciona. Tienes algunos errores de concepto, te recomiendo seguir el curso http://aprenderaprogramar.com/index.php?option=com_content&view=category&id=68&Itemid=188

El código que he probado y parece que funciona es:

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

public class Program6
{
    private static Scanner keyboard = new Scanner(System.in);

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

        final int MAX_SIZE = 100;
        int numOfArray;
        Fan[] fans = new Fan[MAX_SIZE];
        numOfArray = fillArray(fans, MAX_SIZE);
        listFanData(fans, numOfArray);
    }
    public static int fillArray(Fan[] followers, int max) throws IOException
    {
        String fileName;
        int count = 0;
        int i = 1;
        int a = 0;
        String[] names = new String[max];
        int[] ages = new int[max];

        System.out.print("Enter the file name:\n\n ");
        //fileName = keyboard.nextLine();

        // open the file
        File theFile = new File("FanData.txt");

        // make sure the file exists
        if (!theFile.exists())
            System.out.println("File  + fileName +  not found");

        else
        {
            //create a scanner object for to read the file
            Scanner inputFile = new Scanner(theFile);

            // use a while loop that process the document information
            while (inputFile.hasNext() && count < followers.length)
            {
                if (i*2-1 == count) {
                    ages[a] = Integer.parseInt(inputFile.nextLine());
                    i++;
                    a++;
                }

                else {
                    names[a] = inputFile.nextLine();
                    System.out.println("Extraido "+names[a]);
                }
                count++;
            }

            // close the file
            inputFile.close();

            for (int j = 0; j <= (count / 2); j++)            {
                followers[j] = new Fan(names[j], ages[j]);

            }
            System.out.println("There are " + (count / 2) + " fans.");
        }
        return (count / 2);
    }
    public static void listFanData(Fan[] follow, int num) throws IOException
    {

        System.out.println("\nList all Mr. Rogeres' fans");

        for (int i = 0; i <= num; i++) {
            System.out.println(follow[i].getName());
            System.out.println(follow[i].getAge());
        }
    }
}

Saludos!!
Responsable de departamento de producción aprenderaprogramar.com

 

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".