He intentado actualizar mis habilidades de Java para utilizar Java 5 & Java 6. He estado jugando con algunos ejercicios de programación. Me pidieron que leyera en un párrafo de un archivo de texto y sacara una lista ordenada (descendente) de palabras y sacara el conteo de cada palabra.¿Más eficiente o más moderno? Lectura y clasificación de un archivo de texto con Java
Mi código está por debajo.
Mis preguntas son:
Es mi rutina de entrada de archivo el más respetuoso de los recursos de JVM?
¿Es posible reducir los pasos en lo que respecta a leer el contenido del archivo y obtener el contenido en una colección que puede hacer una lista ordenada de palabras?
¿Estoy usando las clases de Colección e interfaz de la manera más eficiente que puedo?
Muchas gracias por cualquier opinión. Solo intento divertirme un poco y mejorar mis habilidades de programación.
import java.io.*;
import java.util.*;
public class Sort
{
public static void main(String[] args)
{
String sUnsorted = null;
String[] saSplit = null;
int iCurrentWordCount = 1;
String currentword = null;
String pastword = "";
// Read the text file into a string
sUnsorted = readIn("input1.txt");
// Parse the String by white space into String array of single words
saSplit = sUnsorted.split("\\s+");
// Sort the String array in descending order
java.util.Arrays.sort(saSplit, Collections.reverseOrder());
// Count the occurences of each word in the String array
for (int i = 0; i < saSplit.length; i++)
{
currentword = saSplit[i];
// If this word was seen before, increase the count & print the
// word to stdout
if (currentword.equals(pastword))
{
iCurrentWordCount ++;
System.out.println(currentword);
}
// Output the count of the LAST word to stdout,
// Reset our counter
else if (!currentword.equals(pastword))
{
if (!pastword.equals(""))
{
System.out.println("Word Count for " + pastword + ": " + iCurrentWordCount);
}
System.out.println(currentword);
iCurrentWordCount = 1;
}
pastword = currentword;
}// end for loop
// Print out the count for the last word processed
System.out.println("Word Count for " + currentword + ": " + iCurrentWordCount);
}// end funciton main()
// Read The Input File Into A String
public static String readIn(String infile)
{
String result = " ";
try
{
FileInputStream file = new FileInputStream (infile);
DataInputStream in = new DataInputStream (file);
byte[] b = new byte[ in.available() ];
in.readFully (b);
in.close();
result = new String (b, 0, b.length, "US-ASCII");
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}// end funciton readIn()
}// end class Sort()
/////////////////////////////////////////////////
// Updated Copy 1, Based On The Useful Comments
//////////////////////////////////////////////////
import java.io.*;
import java.util.*;
public class Sort2
{
public static void main(String[] args) throws Exception
{
// Scanner will tokenize on white space, like we need
Scanner scanner = new Scanner(new FileInputStream("input1.txt"));
ArrayList <String> wordlist = new ArrayList<String>();
String currentword = null;
String pastword = null;
int iCurrentWordCount = 1;
while (scanner.hasNext())
wordlist.add(scanner.next());
// Sort in descending natural order
Collections.sort(wordlist);
Collections.reverse(wordlist);
for (String temp : wordlist)
{
currentword = temp;
// If this word was seen before, increase the count & print the
// word to stdout
if (currentword.equals(pastword))
{
iCurrentWordCount ++;
System.out.println(currentword);
}
// Output the count of the LAST word to stdout,
// Reset our counter
else //if (!currentword.equals(pastword))
{
if (pastword != null)
System.out.println("Count for " + pastword + ": " +
CurrentWordCount);
System.out.println(currentword);
iCurrentWordCount = 1;
}
pastword = currentword;
}// end for loop
System.out.println("Count for " + currentword + ": " + iCurrentWordCount);
}// end funciton main()
}// end class Sort2
Lo primero que se destaca es su fondo C++. Puede obtener más de los ejercicios si intenta hacer que sus soluciones estén orientadas a objetos, incluso si las preguntas no lo solicitan específicamente. Hacerlo más orientado a objetos lo hará pensar acerca de cómo agrupar la funcionalidad en clases lógicas y ocultar detalles de implementación detrás de llamadas a métodos más convenientes. Dicho esto, es hora de leer más sobre su código y abordar su pregunta más directamente ... –
sus convenciones de nombres son atroces para Java moderno. La notación húngara que no es uniforme no es idiomática para Java de ninguna versión. El uso directo de 'Array' también está mal visto, hay clases' List' y 'Set' que son más idiomáticas también. –
Jarrod. Entiendo el comentario sobre la notación húngara. ¿Por qué las clases List o Set son mejores que usar una matriz en esta situación? – Steve