打印一个n * n数字表?

时间:2014-11-25 03:13:54

标签: java variables if-statement for-loop

当用户给出最后一个数字时,如何打印出一个数字表,并将变量加在一起以获得新变量?例如,如果用户为numberOfRows提供值3,则示例输出为;

           1          2          3

1          2          3          4

2          3          4          5

3          4          5          6

这是我到目前为止所拥有的:

        int numberOfRows;
        int numberOfVariables = numberOfRows*numberOfRows;
        int i = 0;

        boolean cycle = false;
        if(i < numberOfVariables){
            cycle = true;
            i++;
        } else if(i >= numberOfVariables){
            cycle = false;
            i++;
        }

        System.out.println(cycle);

        for(cycle = true;;){

            System.out.println(i + "\t");
            i++;

        }

我不确定如何继续。

2 个答案:

答案 0 :(得分:2)

public static void main(String args[]) throws NumberFormatException,
        IOException {

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter number of rows : ");
    int n = Integer.parseInt(reader.readLine());
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n + i; j++) {
            System.out.print(j + "\t");
        }
        System.out.println();
    }
}

输出: 输入行数:6 0 1 2 3 4 5
1 2 3 4 5 6
2 3 4 5 6 7
3 4 5 6 7 8
4 5 6 7 8 9
5 6 7 8 9 10

答案 1 :(得分:0)

public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Wnter row count");
        int numberOfRows = scanner.nextInt();
        for (int i = 0 ; i <= numberOfRows ; i++) {
            for (int j = 0 ; j <= numberOfRows ; j++) {
                System.out.print(i + j + "  ");
            }
            System.out.println();
        }
    }
}

<强>输出

Wnter row count
3
0  1  2  3  
1  2  3  4  
2  3  4  5  
3  4  5  6