The purpose of the program is to read a 2d array from a file and transpose it. I have the transposing part done. How do I read the file into the array? The array that I need to work with is 5x5

import java.util.*;
import java.io.*;
public class prog464d{
  public static void main(String args[]) throws IOException{
    final int[][] original = new int[][] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
    for (int i = 0; i < original.length; i++) {
      for (int j = 0; j < original[i].length; j++) {
        System.out.print(original[i][j] + " ");
      }
      System.out.print("\n");
    }
    System.out.print("\n\n matrix transpose:\n");
    // transpose
    if (original.length > 0) {
      for (int i = 0; i < original[0].length; i++) {
        for (int j = 0; j < original.length; j++) {
          System.out.print(original[j][i] + " ");
        }
        System.out.print("\n");
      }
    }
  }
}

没有正确的解决方案

其他提示

you can do it like down below. I've heard that not many people use the .split() String method, but I love using it haha. you're gonna have to import java.io.File, java.io.FileNotFoundException, and java.util.Scanner. Also, this is assuming that the text file uses tabs as its delimeter. If the text file is a different dimension, just change ROWS and COLS to the new dimensions of the new array

final int ROWS = 5;
final int COLS = 5;

int[][] nums = new int[ROWS][COLS];
// this is used only in java 7 (not java 6)
try (Scanner input = new Scanner(new File("filename.txt"))) {
    int row = -1; // since we're incrementing row at the start of the loop
    while(input.hasNext()) {
        row++;
        String[] line = input.nextLine().split("\t");
        for(int col = 0; col < COLS; col++) {
            try {
                nums[row][col] = Integer.parseInt(line[col]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
    }
} catch (FileNotFoundException e) {
    // do something here
    e.printStackTrace();
}

If you are using Java 6, then the outer try/catch just looks like:

try {
    Scanner input = new Scanner(new File("filename.txt"));
    // insert rest of code here
    input.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String row;
int i=0;
while( (row = br.readLine()) != null ) {
    String[] tokens = row.split(" ");
    int j =0;
    for(String token : tokens) {
        original[i][j++] = Integer.parseInt(token);
    }
}

This is assuming your file looks something like:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

row.split(" ") will return an array of strings. The for loop converts each one to an int and stores it in original.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top