Comprobación de la sangría, encabezado / clase / comentarios en línea, convención de espacios -- java camp codereview Relacionados El problema

Checking indentation, header/class/inline comments, spacing convention


4
vote

problema

Español

Estoy tratando de que mi código se ajuste a la Convención de Formato de Java, creo que he espaciado y sangrado de la manera correcta, sin embargo, su revisión por pares sería muy apreciada.

  /** * @author Nad Deb * Date: 10/10/2020 * This program is used to play two words games * It will work on input from the keyboard to workout suffix/infix/prefix from words * derived from a dictionary text file. */  package wordgames;  //importing classes for method reading files, CLI input and, exception handling  import java.io.File; import java.util.Scanner; import java.io.FileNotFoundException;  public class WordGames { /** * This method is used to declare and initialize a constant class variable  * dictionary. create scanner object class, declare string and int variables also */   private static final File FILEREADER = new File("DICTIONARY.txt"); private static String[] wordCollect; private static int wordCounter = 0; public static Scanner keyboardInput = new Scanner(System.in);  /** * This main method is used to check for file exists with exception handling.  * dictionary. create scanner object class, declare string and int variables also */  public static void main(String[] args) throws FileNotFoundException {     //method for checking if file exists     if (FILEREADER.exists() == false) {     System.out.println("File doesn't exist.  Exiting.");     System.exit(0);     }     wordCollect = new String[100]; Scanner fileScanner = new Scanner(FILEREADER);     while(fileScanner.hasNextLine()) {         String line = fileScanner.nextLine();         wordCollect[wordCounter] = line;         wordCounter++;         }     getSelection(); }  /** * This get selection method is used to handle input from keyboard against a * list of options from the menu, which are linked to methods using switch * case. */  static String getSelection() throws FileNotFoundException {     System.out.println("Welcome to the Word Games program menu.");     System.out.println("Select from one of the following options.");     System.out.println("1. Substring problem.");     System.out.println("2. Points problem.");     System.out.println("3. Exit.");     System.out.println("Enter your selections: ");     String selection = keyboardInput.next();          //case switch for handling menu option input     switch(selection) {         case "1": subStringProblem();         break;         case "2": pointsProblem();         break;         case "3":             System.out.println("Good Bye!");             System.exit(0);         break;         default:             System.out.println("Invalid option.  Try again.");             getSelection();     }     return null; }        /** * This substring method is used to concatenate *fix to end of string temp * which is a string variable input from reading from lines in file via  * wordCollect variable and checks if wordCollect starts with keyboard input * substring. */ static void subStringProblem() throws FileNotFoundException {     System.out.println("Substring problem.");     System.out.println("Enter a Substring:");     String subString = keyboardInput.next();     String notFound = " - not found";  String infixFound = " - infix"; String prefixFound = " - prefix"; String suffixFound = " - suffix";      for(int i = 0; i < wordCounter; i++) {         String temp = wordCollect[i];              boolean found = false;                          if(wordCollect[i].startsWith(subString)) {             found = true;             temp = temp + prefixFound;         }         if(wordCollect[i].endsWith(subString)) {             found = true;             temp = temp + suffixFound;         }         if(wordCollect[i].contains(subString)) {             found = true;             temp = temp + infixFound;         }         if(!found) {             System.out.printf(" " + wordCollect[i] +                                      notFound  + " ");         }                     else {             System.out.printf(" " + temp + " ");         }    }     getSelection(); }   /** * This points problem method is used to read file lines from scanner input. * switch case will check characters= (c) position in word string which is  * input from nextLine, int l is the word length, for statement checks * the characters as it goes along the world.   */ private static void pointsProblem() throws FileNotFoundException   {     System.out.println("Points problem.");     Scanner input = new Scanner(FILEREADER);       while (input.hasNext()) {     String word = input.nextLine();     int l = word.length();     int point = 0;     for (int x = 0; x < 0; x++) {  //checks the letters as it increments         char c = word.charAt(x);   //checks the letter at position x                  switch (c) {             case 'a':             case 'e':             case 'i':             case 'l':             case 'n':             case 'o':             case 'r':             case 's':             case 't':             case 'u':                 point += 1;                 break;             case 'd':             case 'g':                 point += 2;                 break;             case 'b':             case 'c':             case 'm':             case 'p':                 point += 3;                 break;             case 'f':             case 'h':             case 'v':             case 'w':             case 'y':                 point += 4;                 break;              case 'k':                 point += 5;                 break;             case 'j':             case 'x':                     point += 8;                 break;             case 'q':                                     case 'z':                 point += 10;                 break;                                }     }             System.out.println(word + "is worth " + point + " points." );     }     getSelection();                 }   

}

Original en ingles

I'm trying to get my code to conform to java formatting convention, I think I've spaced and indented the right way, however, your peer review would be much appreciated.

/** * @author Nad Deb * Date: 10/10/2020 * This program is used to play two words games * It will work on input from the keyboard to workout suffix/infix/prefix from words * derived from a dictionary text file. */  package wordgames;  //importing classes for method reading files, CLI input and, exception handling  import java.io.File; import java.util.Scanner; import java.io.FileNotFoundException;  public class WordGames { /** * This method is used to declare and initialize a constant class variable  * dictionary. create scanner object class, declare string and int variables also */   private static final File FILEREADER = new File("DICTIONARY.txt"); private static String[] wordCollect; private static int wordCounter = 0; public static Scanner keyboardInput = new Scanner(System.in);  /** * This main method is used to check for file exists with exception handling.  * dictionary. create scanner object class, declare string and int variables also */  public static void main(String[] args) throws FileNotFoundException {     //method for checking if file exists     if (FILEREADER.exists() == false) {     System.out.println("File doesn't exist.  Exiting.");     System.exit(0);     }     wordCollect = new String[100]; Scanner fileScanner = new Scanner(FILEREADER);     while(fileScanner.hasNextLine()) {         String line = fileScanner.nextLine();         wordCollect[wordCounter] = line;         wordCounter++;         }     getSelection(); }  /** * This get selection method is used to handle input from keyboard against a * list of options from the menu, which are linked to methods using switch * case. */  static String getSelection() throws FileNotFoundException {     System.out.println("Welcome to the Word Games program menu.");     System.out.println("Select from one of the following options.");     System.out.println("1. Substring problem.");     System.out.println("2. Points problem.");     System.out.println("3. Exit.");     System.out.println("Enter your selections: ");     String selection = keyboardInput.next();          //case switch for handling menu option input     switch(selection) {         case "1": subStringProblem();         break;         case "2": pointsProblem();         break;         case "3":             System.out.println("Good Bye!");             System.exit(0);         break;         default:             System.out.println("Invalid option.  Try again.");             getSelection();     }     return null; }        /** * This substring method is used to concatenate *fix to end of string temp * which is a string variable input from reading from lines in file via  * wordCollect variable and checks if wordCollect starts with keyboard input * substring. */ static void subStringProblem() throws FileNotFoundException {     System.out.println("Substring problem.");     System.out.println("Enter a Substring:");     String subString = keyboardInput.next();     String notFound = " - not found";  String infixFound = " - infix"; String prefixFound = " - prefix"; String suffixFound = " - suffix";      for(int i = 0; i < wordCounter; i++) {         String temp = wordCollect[i];              boolean found = false;                          if(wordCollect[i].startsWith(subString)) {             found = true;             temp = temp + prefixFound;         }         if(wordCollect[i].endsWith(subString)) {             found = true;             temp = temp + suffixFound;         }         if(wordCollect[i].contains(subString)) {             found = true;             temp = temp + infixFound;         }         if(!found) {             System.out.printf(" " + wordCollect[i] +                                      notFound  + "\n");         }                     else {             System.out.printf(" " + temp + "\n");         }    }     getSelection(); }   /** * This points problem method is used to read file lines from scanner input. * switch case will check characters= (c) position in word string which is  * input from nextLine, int l is the word length, for statement checks * the characters as it goes along the world.   */ private static void pointsProblem() throws FileNotFoundException   {     System.out.println("Points problem.");     Scanner input = new Scanner(FILEREADER);       while (input.hasNext()) {     String word = input.nextLine();     int l = word.length();     int point = 0;     for (int x = 0; x < 0; x++) {  //checks the letters as it increments         char c = word.charAt(x);   //checks the letter at position x                  switch (c) {             case 'a':             case 'e':             case 'i':             case 'l':             case 'n':             case 'o':             case 'r':             case 's':             case 't':             case 'u':                 point += 1;                 break;             case 'd':             case 'g':                 point += 2;                 break;             case 'b':             case 'c':             case 'm':             case 'p':                 point += 3;                 break;             case 'f':             case 'h':             case 'v':             case 'w':             case 'y':                 point += 4;                 break;              case 'k':                 point += 5;                 break;             case 'j':             case 'x':                     point += 8;                 break;             case 'q':                                     case 'z':                 point += 10;                 break;                                }     }             System.out.println(word + "is worth " + point + " points." );     }     getSelection();                 } 

}

  
         
         

Lista de respuestas

3
 
vote
vote
La mejor respuesta
 

Debe usar un formateador automático como sugerido en un comentario, o una en línea, como esta https: //www.tutorialspoint.com/online_java_formatter.htm o https://codebeautify.org/javaviewer

Algunos cambios que obtenemos son

antes

  maxLength3  

después de

  maxLength4  
 

You should use an automatic formatter like suggested in a comment, or an online one such as this https://www.tutorialspoint.com/online_java_formatter.htm or https://codebeautify.org/javaviewer

Some changes that we get are

Before

    switch(selection) {         case "1": subStringProblem();         break;         case "2": pointsProblem();         break; 

After

    switch (selection) {     case "1":       subStringProblem();       break;     case "2":       pointsProblem();       break;  ``` 
 
 
 
 
1
 
vote
  /**  * @author Nad Deb  * Date: 10/10/2020  * This program is used to play two words games  * It will work on input from the keyboard to workout suffix/infix/prefix     from words  * derived from a dictionary text file.  */   

Omitiría tales encabezados de archivo por completo. Hay javadoc a nivel de paquete, pero idealmente información sobre el autor, la fecha, etc. estaría disponible a través del control de la versión.


  package wordgames; 1  

Idealmente, Los nombres de los paquetes asociados con el origen del software, por ejemplo, com.company.application o com.github.username.project .


  //importing classes for method reading files, CLI input and, exception handling   

No comenta lo que estás haciendo, comenta por qué y cómo lo estás haciendo. Tales comentarios son innecesarios, ya que no me dice nada más allá de lo que puedo leer de las siguientes tres líneas.


  /** * This method is used to declare and initialize a constant class variable  * dictionary. create scanner object class, declare string and int variables also */   

mismo aquí, incluso es engañoso, ya que no hay un método para ser visto.


  private static String[] wordCollect; private static int wordCounter = 0;   

Lo más probable es que desee usar un 9988777665544337 / ArrayList y llámelo simplemente 9988777665544339 . El uso de un package wordgames; 0 también le permitiría eliminar el contador.


  package wordgames; 1  

Idealmente, el archivo se pasará a una instancia de su clase, y abriría el 99887766655443312 solo en un alcance según sea necesario.


  package wordgames; 3  

package wordgames; 4 es un último recurso para salir de un JVM. El regreso de package wordgames; 5 significaría que el JVM se apaga, 99887766555443316 significa que el proceso JVM se está terminando.


  package wordgames; 7  

Uso de un package wordgames; 8 Aquí eliminaría la mayor parte de la complejidad, además, leer un archivo se podría realizar a través de package wordgames; 9 , que devuelve un com.company.application020 de todas las líneas. También es posible que deba pensar en la codificación que utiliza el contenido.


  com.company.application1  

En lugar de recursionar, debe bucle hasta que se dé una opción válida.


  com.company.application2  

¿Por qué este devuelve com.company.application3 ?


  com.company.application4  

podría ser reemplazado por un bucle para cada uno cuando se está utilizando un 99887776655443325 .


  com.company.application6  

Como un ejercicio mejorado, codifica el estado en una clase propia. El constructor acepta un com.company.application7 como valor, y hay tres 99887776655443328 / com.company.application9 99887766555433330 que están devolviendo si Estos están presentes. Además, el com.github.username.project1 podría ser anulado para que devuelva la representación de la cadena deseada.


  com.github.username.project2  

Primero, soy un defensor obstinado de que uno nunca debe usar los nombres de las variables de una letra, la única excepción siendo dimensiones.

Segundo, elegir com.github.username.project3 Como nombre de variable es engañoso, ya que la mayoría de las veces, uno pensaría que tendría algo que ver con una dimensión.


  com.github.username.project4  

Ni siquiera está funcionando, en absoluto, la condición es incorrecta.

 
/**  * @author Nad Deb  * Date: 10/10/2020  * This program is used to play two words games  * It will work on input from the keyboard to workout suffix/infix/prefix     from words  * derived from a dictionary text file.  */ 

I'd skip such file headers altogether. There are package-level Javadoc, but ideally infomration about author, date etc. would be available through the version control.


package wordgames; 

Ideally, the package names associate with the origin of the software, for example com.company.application or com.github.username.project.


//importing classes for method reading files, CLI input and, exception handling 

Do not comment what you're doing, comment why and how you're doing it. Such comments are unnecessary as it tells me nothing beyond what I can read from the next three lines.


/** * This method is used to declare and initialize a constant class variable  * dictionary. create scanner object class, declare string and int variables also */ 

Same here, it is even misleading, as there is no method to be seen.


private static String[] wordCollect; private static int wordCounter = 0; 

You most likely want to use a List/ArrayList and call it simply words. Using a List would also allow you to remove the counter.


private static final File FILEREADER = new File("DICTIONARY.txt"); // ... public static Scanner keyboardInput = new Scanner(System.in); 

Ideally the file would be passed to an instance of your class, and you'd open the Scanner only in a scope as needed.


    if (FILEREADER.exists() == false) {     System.out.println("File doesn't exist.  Exiting.");     System.exit(0);     } 

System.exit is a a last resort to exiting a JVM. Returning from main would mean the JVM is shutting down, System.exit means that the JVM process is being terminated.


    wordCollect = new String[100]; Scanner fileScanner = new Scanner(FILEREADER);     while(fileScanner.hasNextLine()) {         String line = fileScanner.nextLine();         wordCollect[wordCounter] = line;         wordCounter++;         } 

Using a List here would remove most of the complexity, additionally, reading a file could be done through java.nio.Files.readAllLines, which returns a List of all lines. You also might need to think about the encoding that is used by the content.


        default:             System.out.println("Invalid option.  Try again.");             getSelection(); 

Instead of recursing, you should loop until a valid option is given.


static String getSelection() throws FileNotFoundException { 

Why does this return String?


    for(int i = 0; i < wordCounter; i++) {         String temp = wordCollect[i]; 

Could be replaced with a for-each loop when a List is being used.


        String temp = wordCollect[i];              boolean found = false;                          if(wordCollect[i].startsWith(subString)) {             found = true;             temp = temp + prefixFound;         }         if(wordCollect[i].endsWith(subString)) {             found = true;             temp = temp + suffixFound;         }         if(wordCollect[i].contains(subString)) {             found = true;             temp = temp + infixFound;         }         if(!found) {             System.out.printf(" " + wordCollect[i] +                                      notFound  + "\n");         }                     else {             System.out.printf(" " + temp + "\n");         } 

As an improved exercise, encode the state in a class of its own. The constructor accepts a String as value, and there are three HasPrefix/HasSuffix/HasInfix methods which are returning whether these are present. Additionally, the toString could be overridden to have it return the wanted String representation.


for (int x = 0; x < 0; x++) 

First, I'm a stubborn advocate that one should never user one-letter variable names, the only exception being dimensions.

Second, choosing x as a variable name is misleading, as most of the time one would think it would have something to do with a dimension.


for (int x = 0; x < 0; x++) { 

That's not even working, at all, the condition is wrong.

 
 

Relacionados problema

6  Encontrar el siguiente palíndromo de una cadena de números  ( Finding the next palindrome of a number string ) 
Aquí está el problema: Un entero positivo se llama palíndromo si su representación en el El sistema decimal es el mismo cuando se lee de izquierda a dere...

2  Eliminación de un nodo en un árbol de búsqueda binario  ( Deletion of a node in a binary search tree ) 
Estoy buscando ver si mi implementación del método de eliminación / eliminación en un árbol de búsqueda binario es suficiente, legible y se ejecuta en un tiem...

5  Memoria / Performance of Merge Sort Code  ( Memory performance of merge sort code ) 
Escribí un código de tipo de combinación para un poco de bocadillo nocturno. Lo he puesto trabajando, pero solo estaba mirando a aprender si me faltaba algo e...

2  Solucionador de rompecabezas de rascacielos en Java [cerrado]  ( Skyscraper puzzle solver in java ) 
cerrado. Esta pregunta es off-topic . Actualmente no está aceptando respuestas. ¿Quieres ...

8  Simple GCD Utility en Java  ( Simple gcd utility in java ) 
i anteriormente discutido El rendimiento se refiere a diferentes algoritmos GCD. Escribí una simple clase de Java que implementa el algoritmo binario GCD. E...

34  Clon a todo color del juego de la vida de Conway, con una GUI decente  ( Full color clone of conways game of life with a decent gui ) 
Escribí esto para aprender Javafx, y como excusa para volver a hacer el juego de la vida. Esta es la gui más compleja que he escrito, así que me gustaría come...

17  Implementación vectorial (física)  ( Vector physics implementation ) 
Recientemente comencé a aprender Java, y decidí implementar un sistema de vectores básico para otro sistema de partículas que estaba construyendo. join()9 ...

5  Encuentre el próximo número Prime - Control de flujo de los bucles anidados 'para `  ( Find the next prime number flow control of nested for loops ) 
Este código funciona perfectamente, pero me molesta. Tener un bucle etiquetado y anidado Bucle, con un Enumerable<T>.Empty()0 Declaración, y un 9988777665...

1  Compruebe si dos cadenas son permutación entre sí  ( Check if two strings are permutation of each other ) 
private String sort(String word) { char[] content = word.toCharArray(); Arrays.sort(content); return new String(content); } private boolea...

2  Fusionar la implementación de Sort Java  ( Merge sort java implementation ) 
¿Puede alguien revisar mi implementación de tipo de fusión en Java? ¿Es bueno / malo y puede mejorarse más? public class MyMergeSort { private int [] d...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos