Posted By

balazs99 on 01/10/14


Tagged


Versions (?)

FileIntoArray


 / Published in: Java
 

2D Array

  1. package fileintoarray;
  2. import java.util.*;
  3. import java.io.*;
  4. /**
  5.  *
  6.  * @author Balazs
  7.  */
  8. public class FileIntoArray{
  9.  
  10. /**
  11.   * @param args the command line arguments
  12.   */
  13. public static void main(String[] args)
  14. // TODO code application logic here
  15. String[][] file;
  16. file = readFileIntoArray("mcpara.t");
  17. tombListazo("File:",file);
  18. }
  19.  
  20. public static String[][] readFileIntoArray(String file)
  21.  
  22. Scanner file1 = new Scanner(new File(file));
  23. Scanner file2 = new Scanner(new File(file));
  24.  
  25. int lineQty = 0;
  26. int maxLineLength = 0;
  27. int wordQty = 0;
  28. int colPos = 0;
  29. int rowPos = 0;
  30.  
  31. String[][] result;
  32. Scanner line;
  33.  
  34. while (file1.hasNextLine()){
  35. wordQty = 0;
  36. lineQty += 1;
  37. line = new Scanner(file1.nextLine());
  38.  
  39. while (line.hasNext()){
  40. wordQty += 1;
  41. line.next();
  42. }
  43.  
  44. if (wordQty > maxLineLength) maxLineLength = wordQty;
  45. }
  46.  
  47. if (lineQty == 0 & maxLineLength == 0)return null;
  48.  
  49. result = new String[lineQty][maxLineLength];
  50.  
  51. while (file2.hasNextLine()){
  52. line = new Scanner(file2.nextLine());
  53. colPos = 0;
  54. while (line.hasNext()){
  55. result[rowPos][colPos++] = line.next();
  56. }
  57. rowPos += 1;
  58. }
  59. return result;
  60.  
  61. }
  62. public static void tombListazo(String cim, String[][] tomb){
  63. System.out.println(cim);
  64.  
  65. for (int i=0 ; i < tomb.length ; i++) {
  66. for (int j=0 ; j < tomb[i].length - 1; j++){
  67. System.out.print(tomb[i][j] + " ");
  68. }
  69. System.out.println(tomb[i][tomb[i].length - 1]);
  70. }
  71. }
  72. }

Report this snippet  

You need to login to post a comment.