英文:
The code that I have tried is not displaying the expected output. How can I rectify my code which is related to patterns?
问题
我需要打印一个正方形的图案,其中数字随着行数递增。例如,考虑变量'i'代表行数的值,如果你初始化i=1,并使用while循环递增值直到用户输入的'n',第一行将打印1,第二行将打印2,依此类推直到达到值'n'。此外,我创建了一个用于列的变量,并将其命名为'j',其值也会递增直到达到'n'。
我得到的输出如下:
我编写的代码是(java):
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int i =1;
while(i<=n){
    int j = 1;
    while(j<=n){
        System.out.println(i);
        j=j+1;
    }
    System.out.println();
    i=i+1;
}
为什么上述代码的输出是:
而不是:
- 1111
 - 2222
 - 3333
 - 4444
 
请帮我解决这个问题。
英文:
I need to print a square pattern where the number increases as per the row, for example consider variable 'i' which represents row value, if you initialize i=1 and increase the value till 'n' which is user input using while loop, the first row will print 1, second row will print 2 and so on till it reaches the value 'n'. Additionally I created variable for column and named it 'j' whose value also increases till it reaches n.
The output that I'm getting though is:
enter image description here
The code that I have written is: (java)
enter image description here
Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        int i =1;
        while(i<=n){
            int j = 1;
            while(j<=n){
                System.out.println(i);
                j=j+1;
            }
            System.out.println();
            i=i+1;
        }
Why is the output for the above code:
enter image description here instead of
- 1111
 - 2222
 - 3333
 - 4444
 
Please help me out.
答案1
得分: 2
问题
文档中说明了以下内容,你知道
> 打印一个整数然后结束该行
修复
改用 print
while (i <= n) {
    int j = 1;
    while (j <= n) {
        System.out.print(i);
        ++j;
    }
    System.out.println();
    ++i;
}
改进
可以用 for 循环更简洁
for (int i = 1; i <= n; ++i) {
    for (int j = 1; j <= n; ++j) {
        System.out.print(i);
    }
    System.out.println();
}
使用 String.repeat
for (int i = 1; i <= n; ++i) {
    System.out.println(Integer.toString(i).repeat(n));
}
英文:
Problem
The doc states the following and you know it
> Prints an integer and then terminates the line
Fix
Use print instead
while (i <= n) {
    int j = 1;
    while (j <= n) {
        System.out.print(i);
        ++j;
    }
    System.out.println();
    ++i;
}
Improvements
Could be a little bit nicer with for loops
for (int i = 1; i <= n; ++i) {
    for (int j = 1; j <= n; ++j) {
        System.out.print(i);
    }
    System.out.println();
}
Using String.repeat
for (int i = 1; i <= n; ++i) {
    System.out.println(Integer.toString(i).repeat(n));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论