Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate through an int

Tags:

java

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();
like image 784
user2803555 Avatar asked Dec 25 '22 09:12

user2803555


2 Answers

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();
    }
}
like image 196
T3 H40 Avatar answered Jan 10 '23 10:01

T3 H40


IntStream.range(0, num).forEach(System.out::println);
like image 24
Michael Rodionov Avatar answered Jan 10 '23 10:01

Michael Rodionov