fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10.  
  11. public static void main (String[] args) throws java.lang.Exception
  12. {
  13. final Thread thread = new Thread(new MatrixRunner());
  14. thread.run();
  15. }
  16.  
  17. //this setup allows for the dropping of the static context beyond 'this' point of execution
  18. private static class MatrixRunner implements Runnable {
  19. public void run() {
  20. final Matrix matrix = new Matrix(3);
  21. System.out.printf("Matrix : %s\n", matrix);
  22. matrix.transpose();
  23. System.out.printf("After transpose : %s\n", matrix);
  24. }
  25.  
  26. //notice this class does not have static modifier
  27. private class Matrix {
  28. private final double[][] matrix;
  29. private final int size;
  30. public Matrix(final int size) {
  31. this.size = size;
  32. matrix = new double[size][size];
  33.  
  34. //populate with dummy data...omitted the 0 as they are assigned by default
  35. matrix[0][0]=1;
  36. matrix[1][0]=5;
  37. matrix[1][1]=1;
  38. matrix[2][0]=6;
  39. matrix[2][1]=5;
  40. matrix[2][2]=1;
  41.  
  42. }
  43.  
  44. public void transpose() {
  45. for(int i = 0; i < size; ++i) {
  46. for(int j = 0; j < i ; ++j) {
  47. double tmpJI = get(j, i);
  48. put(j, i, get(i, j));
  49. put(i, j, tmpJI);
  50. }
  51. }
  52. }
  53.  
  54. public String toString() {
  55. System.out.println();
  56. final StringBuilder sb = new StringBuilder();
  57. for(int i = 0; i < size; ++i) {
  58. for(int j = 0; j < size ; ++j) {
  59. sb.append((int)get(i,j));
  60. sb.append(" ");
  61. }
  62. sb.append("\n");
  63. }
  64. return sb.toString();
  65. }
  66.  
  67. public void put(int i, int j, double d) {
  68.  
  69. matrix[i][j]=d;
  70. }
  71.  
  72. public double get(int i, int j) {
  73.  
  74. return matrix[i][j];
  75. }
  76. }
  77. }
  78.  
  79. }
Success #stdin #stdout 0.08s 380224KB
stdin
Standard input is empty
stdout
Matrix : 
1 0 0 
5 1 0 
6 5 1 

After transpose : 
1 5 6 
0 1 5 
0 0 1