fork download
  1. import java.util.Random;
  2.  
  3. class Main {
  4.  
  5. public static void main(String[] args) {
  6. Random RD = new Random();
  7. int DMax = 5;
  8.  
  9. //オリジナル・データ
  10. int[][] Data = new int[DMax][DMax];
  11. // ↑Dataは使わなくても可能、多少の修正は必要
  12.  
  13. //表示用データ
  14. Integer[][] Synth = new Integer[DMax + 2][DMax + 1];
  15. // ↑Integerはintのラッパークラス
  16.  
  17. int c, r, i;
  18.  
  19. //乱数データの生成
  20. for (r = 0; r < DMax; r++) {
  21. for (c = 0; c < DMax; c++) {
  22. int rd = RD.nextInt(10);
  23. // ↑RD.nextInt(10)の範囲は「0~9」であることに注意
  24. Data[r][c] = rd;
  25. Synth[r + 1][c] = rd;
  26. }
  27. }
  28.  
  29. //行の合計
  30. for (r = 0; r < DMax; r++) {
  31. for (c = 0; c < DMax; c++) {
  32. if (Synth[r + 1][DMax] == null) Synth[r + 1][DMax] = 0;
  33. Synth[r + 1][DMax] += Data[r][c];
  34. }
  35. }
  36.  
  37. //列の合計
  38. for (c = 0; c < DMax; c++) {
  39. for (r = 0; r < DMax; r++) {
  40. if (Synth[DMax + 1][c] == null) Synth[DMax + 1][c] = 0;
  41. Synth[DMax + 1][c] += Data[r][c];
  42. }
  43. }
  44.  
  45. //斜めの合計
  46. for (i = 0; i < DMax; i++) {
  47. if (Synth[DMax + 1][DMax] == null) Synth[DMax + 1][DMax] = 0;
  48. Synth[DMax + 1][DMax] += Data[i][i];
  49. if (Synth[0][DMax] == null) Synth[0][DMax] = 0;
  50. Synth[0][DMax] += Data[DMax - 1 - i][i];
  51. }
  52.  
  53. //表示
  54. for (int sr = 0; sr < Synth.length; sr++) {
  55. for (int sc = 0; sc < Synth[sr].length; sc++) {
  56. if (Synth[sr][sc] == null) {
  57. System.out.print(" ");
  58. } else {
  59. System.out.printf("%3d", Synth[sr][sc]);
  60. }
  61. }
  62. System.out.println();
  63. }
  64. }
  65. }
  66.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty