6

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 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();
user2803555
  • 161
  • 2
  • 2
  • 10
  • what do you mean if `i=5`, then does you want `i` reach to like `1` as 1 length or `5` as val. ? like wise for `i=10` then `10` or `2`.!! – bNd Jan 28 '16 at 06:55
  • 3
    What did you expect the "length" a number to be anyway? – Jon Skeet Jan 28 '16 at 06:56

4 Answers4

9

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

Your num already is a number. 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


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:

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();
    }
}
Community
  • 1
  • 1
T3 H40
  • 2,326
  • 8
  • 32
  • 43
4
IntStream.range(0, num).forEach(System.out::println);
  • 4
    Welcome to Stack Overflow. While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. [How to Answer](https://stackoverflow.com/help/how-to-answer) – Elletlar Oct 30 '20 at 21:43
2

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);
            }
        }
    }
}
user2173372
  • 483
  • 7
  • 17
1
  1. Using Integer.toString Method
        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;    
    }