java 我如何遍历一个 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35054621/
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
How do I iterate through an int
提问by user2803555
I get an "int cannot be dereferenced" It might be because .lenght on it, What else can I do to iterate through the int?
我得到一个“int 不能被取消引用”这可能是因为 .lenght 在它上面,我还能做些什么来遍历 int?
int num;
System.out.print("Enter a positive integer: ");
num = console.nextInt();
if (num > 0)
for (int i = 0; i < num.lenght; i++)
System.out.println();
回答by T3 H40
for (int i = 0; i < num; i++)
for (int i = 0; i < num; i++)
Your num
already is a number. So your condition will suffice like above.
你num
已经是一个数字。所以你的条件就足够了。
Example:If the user enters 4
, the for statement will evaluate to
for (int i = 0; i < 4; i++)
, running the loop four times, with i
having the values 0, 1, 2
and 3
示例:如果用户输入4
,for 语句将评估为
for (int i = 0; i < 4; i++)
,运行循环四次,i
具有值0, 1, 2
和3
If you wanted to iterate over each digit, you would need to turn your int back to a stringfirst, and then loop over each characterin this string:
如果你想遍历每个数字,你需要先把你的int 转回一个字符串,然后循环这个字符串中的每个字符:
String numberString = Integer.toString(num);
for (int i = 0; i < numberString.length(); i++){
char c = numberString.charAt(i);
//Process char
}
If you wanted to iterate the binary representationof your number, have a look at thisquestion, it might help you.
如果你想迭代你的数字的二进制表示,看看这个问题,它可能对你有帮助。
Note:though it might not be required, I would suggest you to use {}
-brackets around your statement blocks, to improve readability and reduce chance of mistakes like this:
注意:虽然可能不是必需的,但我建议您{}
在语句块周围使用-brackets,以提高可读性并减少出现以下错误的机会:
if (num > 0) {
for (int i = 0; i < num; i++) {
System.out.println();
}
}
回答by user2173372
Try the following code:
试试下面的代码:
import java.util.Scanner;
public class IntExample {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int num = console.nextInt();
console.close();
if (num > 0) {
for (int i = 0; i < num; i++) {
System.out.println(i);
}
}
}
}