sebagmi
sebagmi

Reputation: 13

How to display n by n square pattern from numbers 1 through nine then 0 in Java

I have already tried putting values in an array, using matrices and even using recursive arrays but those only return error to me.

Now the code I have made looks like this

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();
    }
}

The input for instance has to look like this if the entered value for n is 4:

1234

5678

9012

Upvotes: 1

Views: 376

Answers (3)

Wasi Ahmad
Wasi Ahmad

Reputation: 37741

You don't have a method in your class. I don't know whether you didn't put it mistakenly or not! But the following worked.

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();
    }
}

For input 5, it outputs:

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 

Upvotes: 1

Stan
Stan

Reputation: 1430

I don't really think you need array just to print values. You can simply have counter and rest it once it more that 9. Something like that:

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();
}

Upvotes: 1

Eric Duminil
Eric Duminil

Reputation: 54263

You just need to use modulo to start back at 0 after 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();
    }
}

For example :

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: Don't forget to close your scanner.

Upvotes: 1

Related Questions