-1

How would I read the input of a file, turn it into a two-dimensional array, and flip it horizontally?

This is all I really have since I don't know how to get started:

import java.util.Scanner;
import java.io.*:
import java.util.*:

public class project1 {

   public static void main(String[] args) {

       String[][] myString = new String [row][column];
Mureinik
  • 297,002
  • 52
  • 306
  • 350
Miguel Pinedo
  • 45
  • 1
  • 6
  • So how is the input formatted? – Bubletan Apr 20 '15 at 12:19
  • You start by learning how to do file access in Java. Then you learn how to parse input; most likely, that might boil down to split a string into substrings. Then you learn about java arrays. In other words: what exactly is the problem you are struggling with? As of now, it sounds more like: "I got my assignment here; please do all the work for me". – GhostCat Apr 20 '15 at 12:21
  • Well the problem is really that I have no idea how to input a file. Is there some generic way to read a file without knowing the location? I know there is a readfile method but doesn't that require the file location? – Miguel Pinedo Apr 20 '15 at 12:30

1 Answers1

0

use this function to read the matrix:

 public static int[][] create2DIntMatrixFromFile(String filename) throws Exception {
        int[][] matrix = null;

        // If included in an Eclipse project.
        InputStream stream = ClassLoader.getSystemResourceAsStream(filename);
        BufferedReader buffer = new BufferedReader(new InputStreamReader(stream));

        // If in the same directory - Probably in your case...
        // Just comment out the 2 lines above this and uncomment the line
        // that follows.
        //BufferedReader buffer = new BufferedReader(new FileReader(filename));

        String line;
        int row = 0;
        int size = 0;

        while ((line = buffer.readLine()) != null) {
            String[] vals = line.trim().split("\\s+");

            // Lazy instantiation.
            if (matrix == null) {
                size = vals.length;
                matrix = new int[size][size];
            }

            for (int col = 0; col < size; col++) {
                matrix[row][col] = Integer.parseInt(vals[col]);
            }

            row++;
        }

        return matrix;
    }     

and this one to transpose it

 public static double[][] transposeMatrix(double [][] m){
        double[][] temp = new double[m[0].length][m.length];
        for (int i = 0; i < m.length; i++)
            for (int j = 0; j < m[0].length; j++)
                temp[j][i] = m[i][j];
        return temp;
    }

references:

Read .txt file into 2D Array

transpose double[][] matrix with a java function?

Community
  • 1
  • 1