英文:
Java: How can I fix this nested loops
问题
从输入中读取整数 inputNum。对于从 1 到 inputNum 的每个数字,输出该数字,然后输出相应数量的井号字符('#')。在每个输出的末尾加上换行符。
例如,如果输入是 5,则输出如下:
1#
2##
3###
4####
5#####
import java.util.Scanner;
public class LoopPatterns {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int inputNum;
int i;
int j;
inputNum = scnr.nextInt();
for (i = 1; i <= inputNum; ++i) {
System.out.print(i);
for (j = 1; j <= i; ++j) {
System.out.print("#");
}
System.out.println();
}
}
}
英文:
Integer inputNum is read from input. For each number from 1 to inputNum, output the number followed by the number's value of hashtag characters ('#'). End each output with a newline.
Ex: If the input is 5, then the output is:
1#
2##
3###
4####
5#####
This is what I tried but the problem is that I don't know how to fix it so in the output, the character (in this case "#") is applied as many times as the number.
for instance, for input 5, my output was:
1#####
2#####
3#####
4#####
5#####
import java.util.Scanner;
public class LoopPatterns {
public static void main (String[] args) {
Scanner scnr = new Scanner(System.in);
int inputNum;
int i;
int j;
inputNum = scnr.nextInt();
for (i = 1; i <= inputNum; ++i){
System.out.print(i);
for (j = inputNum; j >= 1; --j){
System.out.print("#");
}
System.out.println();
}
}
}
答案1
得分: 4
内部循环应该从i
开始递减。像这样:
for (i = 1; i <= inputNum; ++i) {
System.out.print(i);
for (j = i; j >= 1; --j) {
System.out.print("#");
}
System.out.println();
}
英文:
The inner loop should count down from i
. Like,
for (i = 1; i <= inputNum; ++i) {
System.out.print(i);
for (j = i; j >= 1; --j) {
System.out.print("#");
}
System.out.println();
}
答案2
得分: 0
请尝试这个,您将会得到以下结果:1# 2## 3### 4#### 5#####
public class LoopPattern {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("输入一个数字");
int inputNum = s.nextInt();
for (int i = 1; i <= inputNum; i++) {
System.out.print(i);
for (int j = 1; j <= i; j++) {
System.out.print("#");
}
System.out.print(" ");
}
}
}
英文:
Please try this, you will get following result: 1# 2## 3### 4#### 5#####
public class LoopPattern {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the number");
int inputNum = s.nextInt();
for(int i=1; i<=inputNum; i++) {
System.out.print(i);
for(int j=1; j<=i;j++) {
System.out.print("#");
}
System.out.print(" ");
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论