shamusd
shamusd

Reputation: 1

starting a for loop on the last digit of an integer pulled from a scanner (java)

I'm trying to get a for loop to start on the last digit of an integer that is given by the user through scanner. Any suggestions?

for(int i = number.length()-1;...)

I'm looking for something along those lines but that won't leave me with a compile error

Upvotes: 0

Views: 176

Answers (2)

Bohemian
Bohemian

Reputation: 425033

Use integer arithmetic:

for (int i = number, digit = i % 10; i > 0; i = i / 10, digit = i % 10) {
    // do something with "digit", which will iterate from last digit to first 
}

Here's some sample code showing it working:

int number = 1234567890;
for (int i = number, digit = i % 10; i > 0; i = i / 10, digit = i % 10) {
    System.out.println(digit);
}

Output:

0
9
8
7
6
5
4
3
2
1

Upvotes: 1

Kevin Bowersox
Kevin Bowersox

Reputation: 94469

You must convert the number to a String then iterate through each character.

public class IterateNumber {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter a number:");
        String num = String.valueOf(scanner.nextInt());

        for(int i = num.length()-1; i >= 0; i--){
            System.out.println(num.charAt(i));
        }
    }
}

Upvotes: 1

Related Questions