2016-12-05 58 views
1

我已經嘗試將值放在數組中,使用矩陣甚至使用遞歸數組,但這些只會向我返回錯誤。如何從數字1到9然後在Java中顯示n從n到n的方形圖案

現在我所做的代碼看起來像這樣

import java.util.*; 
public class SQf1t9t0 { 
    int n, i, j; 

    Scanner yar = new Scanner(System.in); 
    System.out.println("Enter size for n square: "); 
    n = yar.nextInt(); 

    int[][] f19t0 = new int[n][n]; 
    for (i = 0; i < n; i++) 
    { 
     for (j = 0; j < n; j++) 
     { 
      f19t0[i][j] = i+1; 
      System.out.print(f19t0[i][j] + " "); 
     } 
     System.out.println(); 
    } 
} 

例如輸入有這個樣子,如果n的輸入的值是4:

1234 

5678 

9012 
+0

你'f19t0'和'之間在'j'循環的空間[i] [j]'。它可能會拋出你的錯誤。 –

+1

change f19t0 [i] [j] = i + 1;到f19t0 [i] [j] = i * n + j + 1; –

+1

並將'f19t0 [i] [j] = i * n + j + 1'改爲'f19t0 [i] [j] =(i * n + j + 1)%10' – Fefux

回答

1

我真的不認爲你需要數組來打印數值。你可以簡單地有櫃檯和休息一次更是9.類似的東西:

int counter = 0; 
for (i = 0; i < n; i++) 
{ 
    for (j = 0; j < n; j++) 
    { 
    System.out.print(counter); 
    if(++counter > 9) { 
     counter = 0; 
    } 
    } 
    System.out.println(); 
} 
1

你只需要使用模後9.

import java.util.Scanner; 


public class DisplayMatrix 
{ 
    public static void main(String[] args) { 
     int n, i, j; 

     Scanner yar = new Scanner(System.in); 
     System.out.println("Enter size for n square: "); 
     n = yar.nextInt(); 

     int[][] f19t0 = new int[n][n]; 
     for (i = 0; i < n; i++) { 
      for (j = 0; j < n; j++) { 
       f19t0[i][j] = (i * n + j + 1) % 10; 
       System.out.print(f19t0[i][j] + " "); 
      } 
      System.out.println(); 
     } 
     yar.close(); 
    } 
} 

例如啓動回0:

Enter size for n square: 
6 
1 2 3 4 5 6 
7 8 9 0 1 2 
3 4 5 6 7 8 
9 0 1 2 3 4 
5 6 7 8 9 0 
1 2 3 4 5 6 

PS:不要忘記關閉掃描儀。

1

你不必在你的類中的方法。我不知道你是不是把它弄錯了!但以下工作。

import java.util.*; 

public class test { 

    public static void main(String[] args) { 
     int n, i, j; 

     Scanner yar = new Scanner(System.in); 
     System.out.println("Enter size for n square: "); 
     n = yar.nextInt(); 

     int[][] f19t0 = new int[n][n]; 
     for (i = 0; i < n; i++) { 
      for (j = 0; j < n; j++) { 
       f19t0[i][j] = (i*n+j+1) % 10; 
       System.out.print(f19t0[i][j] + " "); 
      } 
      System.out.println(); 
     } 
     yar.close(); 
    } 
} 

對於輸入5,它輸出:

Enter size for n square: 
5 
1 2 3 4 5 
6 7 8 9 0 
1 2 3 4 5 
6 7 8 9 0 
1 2 3 4 5