Foros aprenderaprogramar.com
Aprender a programar => C, C++, C#, Java, Visual Basic, HTML, PHP, CSS, Javascript, Ajax, Joomla, MySql y más => Mensaje iniciado por: Alanespartan en 08 de Octubre 2017, 03:25
-
Hola a todos, lo que quiero hacer es un programa que me lea los números que hay dentro de un documento txt y los guarde dentro de un array, cabe decir que la dirección del documento la debe introducir el usuario.
Les adjunto mi código
import java.util.Scanner;
public class ReadFile{
public static void main(String[] args) {
// Initialize the variables
String fileDirection;
// Creating Objects
Scanner keyboard = new Scanner(System.in);
Numbers newArch = new Numbers();
// Asking for the direction of the file
System.out.println("\n\n*--- Give me the location of your text document ---*");
System.out.println("Here's an example of what do you need to put: C:\\Users\\Example\\Documents\\File.txt");
fileDirection = keyboard.nextLine();
// Sending the direction of the file
newArch.readTxt(fileDirection);
// Here we print the numbers of the document
System.out.println("\nThese are the numbers of your document :) \n\n");
newArch.printArray();
}
}
import java.util.Scanner;
import java.util.Arrays;
import java.io.File;
public class Numbers{
// Creating an empty array
int docNumbers[];
public void readTxt(String direction){
// We create a temporal variable to save the numbers
int num = 0, count = 0;
Scanner myArch = null;
try{
myArch = new Scanner(new File(direction));
}catch(Exception e){
System.out.println("Document not found");
}
// This loop ends until readBuffer runs out of data (numbers)
while(myArch.hasNext()){
num = myArch.nextInt();
docNumbers[count] = num;
count++;
}
}
// This method is to display the numbers of the array
public void printArray(){
System.out.println(Arrays.toString(docNumbers));
}
public Numbers(){
}
}
-
Buenas, al ejecutar el código salta un error java.lang.NullPointerException
Esta excepción te la lanza porque el array no está inicializado.
Puedes ver un ejemplo de funcionamiento poniendo en el constructor algo como esto:
public Numbers(){
docNumbers = new int[100];
}
Al escribir esto ya no te lanzará el error. En este caso te permitiría poner en el archivo hasta 100 números aunque esto no es una solución ideal. Pueden pensarse en otras maneras de tener una lista dinámica que te permita no tener posiciones fijas en el array.
Para esto hacen falta conceptos básicos de Java, te recomiendo consultar los siguientes cursos:
Curso básico de Java: https://aprenderaprogramar.com/index.php?option=com_content&view=category&id=68&Itemid=188
Curso avanzado: https://aprenderaprogramar.com/index.php?option=com_content&view=category&id=58&Itemid=180
Salu2