简体   繁体   English

我如何遍历一个int

[英]How do I iterate through an int

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 cannot be dereferenced”这可能是因为它的长度,我还能做些什么来遍历 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();

for (int i = 0; i < num; i++)

Your num already is a number.你的num已经是一个数字了。 So your condition will suffice like above.所以你的条件就足够了。

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, 23


If you wanted to iterate over each digit, you would need to turn your int back to a string first, and then loop over each character in 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 representation of your number, have a look at this question, 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:注意:虽然它可能不是必需的,但我建议您在语句块周围使用{}括号,以提高可读性并减少出现以下错误的机会:

if (num > 0) {
    for (int i = 0; i < num; i++) {
        System.out.println();
    }
}

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);
            }
        }
    }
}
  1. Using Integer.toString Method使用Integer.toString方法
        int num = 110102;
        String strNum = Integer.toString(num);
        for (int i = 0; i < strNum.length(); i++) {
            System.out.println(strNum.charAt(i));
        }
  1. Using Modulo Operator `使用运算符`
    int num = 1234;
    while(num>0) {
       int remainder = num % 10;
       System.out.println(remainder);
       num = num / 10;    
    }
IntStream.range(0, num).forEach(System.out::println);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM