java 编写一个打印 1 2 ... userNum 的 For 循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35543564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing a For loop that prints 1 2 ... userNum?
提问by Luke Harding
I am not sure what I am doing wrong here. Here is the original prompt:
我不确定我在这里做错了什么。这是原始提示:
"Write a for-loop
that prints: 1 2 .. userNum. Print a space after each number, including after the last number. Ex: userNum = 4
prints:
1 2 3 4
"
“写一个for-loop
打印:1 2 .. userNum。在每个数字之后打印一个空格,包括最后一个数字之后。例如:userNum = 4
打印:
1 2 3 4
”
Here is my code:
这是我的代码:
import java.util.Scanner;
public class CountToNum {
public static void main (String [] args) {
int userNum = 0;
int i = 0;
userNum = 4;
for (userNum = 1; userNum <= 4; ++userNum) {
System.out.print(userNum + " ");
}
System.out.println("");
return;
}
}
回答by mech
Your for-loop
needs to use two different variables, one for checking against, and one for incrementing. You're also incrementing your variable before running the loop (++userNum
), which means that you're counting from 2 to 4 instead of 1 to 4 like you meant to.
您for-loop
需要使用两种不同的变量,一种用于检查,另一种用于递增。您还在运行循环 ( ++userNum
)之前增加了变量,这意味着您从 2 到 4 计数,而不是像您打算的那样从 1 到 4。
So, in your case, you would do the following:
因此,在您的情况下,您将执行以下操作:
for (i = 1; i <= userNum; i++) {
System.out.print(i + " ");
}
回答by Flikk
for (i = 1; i <= userNum; i++) {
System.out.print(i + " ");
}
What else did you declare i
for?
You should use it when you declare it ;)
你还申报i
了什么?您应该在声明时使用它;)
回答by ifly6
To print a range of numbers using a for-loop from 1 to a provided ending point, use this:
要使用从 1 到提供的结束点的 for 循环打印一系列数字,请使用以下命令:
for (int x = 0; x <= end; x++) {
System.out.println(x + " ");
}
I believe that the problem with the code that you presented is that you're mixing up the ending point (where you call it userNum
) and the temporary variable with which you iterate (which I call x
, though different conventions may use i
).
我相信您提供的代码的问题在于您混淆了终点(您称之为userNum
)和迭代的临时变量(我称之为x
,尽管可能使用不同的约定i
)。