5

So basically i am trying to read a .txt file that contains these following in it:

3 5 

2 3 4 5 10

4 5 2 3 7

-3 -1 0 1 5

and store them into 2D array and print it on console, what i got from the console is fine but only missing the first row 3 5, which i do not know what is wrong with my code made it ignored the first line. what i got as output now:

2  3  4  5 10 

4  5  2  3  7

-3 -1  0  1  5 

import java.io.*;
import java.util.*;

public class Driver0 {
    public static int[][] array;
    public static int dimension1, dimension2;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Welcome to Project 0.");
        System.out.println("What is the name of the data file? ");
        String file = input.nextLine();
        readFile(file);
    }

    public static void readFile(String file) {
        try {
            Scanner sc = new Scanner(new File(file));
            dimension1 = sc.nextInt();
            dimension2 = sc.nextInt();
            array = new int[dimension1][dimension2];
            while (sc.hasNext()) {
                for (int row = 0; row < dimension1; row++) {
                    for (int column = 0; column < dimension2; column++) {
                        array[row][column] = sc.nextInt();
                        System.out.printf("%2d ", array[row][column]);
                    }
                    System.out.println();
                }

            }
            sc.close();
        }

        catch (Exception e) {
            System.out
            .println("Error: file not found or insufficient     requirements.");
        }
    }
}
Watermel0n
  • 241
  • 2
  • 10
Sylvia Wang
  • 81
  • 2
  • 5
  • you'll miss the first two numbers cuz you're getting them in these two lines : `dimension1 = sc.nextInt()` and `dimension2 = sc.nextInt()`, you're using them as dimensions of your array. – La VloZ Jun 13 '15 at 02:14

5 Answers5

1

You're reading those numbers in this part of your code:

dimension1 = sc.nextInt();
dimension2 = sc.nextInt();

So dimension1 gets the value of 3 and dimension2gets the value of 5, but you're not saving them into the array.

David Mendez
  • 157
  • 12
1

Try this code....

import java.io.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;

public class Proj4 {
    public static int rows, cols;
    public static int[][] cells;
    /**
     * main reads the file and starts
     * the graphical display
     */
    public static void main(String[] args) throws IOException {
        Scanner s = new Scanner(System.in);
        String file = JOptionPane.showInputDialog(null, "Enter the input file name: ");
        Scanner inFile = new Scanner(new File(file));

        rows = Integer.parseInt(inFile.nextLine());
        cols = Integer.parseInt(inFile.nextLine());
        cells = new int[rows][cols];

                //this is were I need help
        for(int i=0; i < rows; i++) 
        {
            String line = inFile.nextLine();
            line = line.substring(0);

        }

        inFile.close();

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.print(cells[i][j]);
            }
            System.out.print();
    }
Jaffer Wilson
  • 7,029
  • 10
  • 62
  • 139
1

You can use Stream API to do it easily

public static Integer[][] readFile(String path) throws IOException {
    return Files.lines(Paths.get(path)) // 1
            .filter(line -> !line.trim().isEmpty()) // 2
            .map(line -> Arrays.stream(line.split("[\\s]+")) // 3
                    .map(Integer::parseInt) // 4
                    .toArray(Integer[]::new)) // 5
            .toArray(Integer[][]::new); // 6
}
  1. Read the file as Stream of Lines
  2. Ignore empty lines
  3. Split each line by spaces
  4. Parse splitted String values to get Integer values
  5. Create an array of Integer values
  6. Collect it in 2D-Array
Ilya Tatsiy
  • 185
  • 2
  • 8
0

The first two values are being saved into dimension1 and dimension2 variables, so when sc.nextInt gets called later, it's already read the first two numbers and moves on to the next line. So those first ints don't make it into the array.

Ryan R
  • 13
  • 6
0

A few things to consider:

  1. You're wanting to use the entire file, so I would read the whole thing in at once with Files.readAllLines(). This function returns a List<String> which will have all the lines to your file. If there are any blank lines, remove them and now you have the number of rows to declare for your 2d array.
  2. Each line is space delimited, so a simple String.split() on each line in your List<String> will give you the number of columns each row should have.
  3. Splitting each line and converting them to integers can be done with a nested for loops which is normal for processing 2d arrays.

For Example:

public static void main(String[] args) throws Exception {
    // Read the entire file in
    List<String> myFileLines = Files.readAllLines(Paths.get("MyFile.txt"));

    // Remove any blank lines
    for (int i = myFileLines.size() - 1; i >= 0; i--) {
        if (myFileLines.get(i).isEmpty()) {
            myFileLines.remove(i);
        }
    }

    // Declare you 2d array with the amount of lines that were read from the file
    int[][] intArray = new int[myFileLines.size()][];

    // Iterate through each row to determine the number of columns
    for (int i = 0; i < myFileLines.size(); i++) {
        // Split the line by spaces
        String[] splitLine = myFileLines.get(i).split("\\s");

        // Declare the number of columns in the row from the split
        intArray[i] = new int[splitLine.length]; 
        for (int j = 0; j < splitLine.length; j++) {
            // Convert each String element to an integer
            intArray[i][j] = Integer.parseInt(splitLine[j]);
        }
    }

    // Print the integer array
    for (int[] row : intArray) {
        for (int col : row) {
            System.out.printf("%5d ", col);
        }
        System.out.println();
    }
}

Results:

    3     5 
    2     3     4     5    10 
    4     5     2     3     7 
   -3    -1     0     1     5
Shar1er80
  • 9,001
  • 2
  • 20
  • 29