Separating the Digits in an Integer - exercise from Deitel's Java book

前端 未结 10 622
忘了有多久
忘了有多久 2020-12-22 13:44

Exercise from Deitel\'s \"Java How To Program\" 10th edition:

2.30 (Separating the Digits in an Integer) Write an application that inputs one number c

10条回答
  •  南方客
    南方客 (楼主)
    2020-12-22 14:26

    Try this:

    import java.util.*;
    public class DigitsDisplay
    {
        public static void main (String[] args)
        {
            Scanner input = new Scanner (System.in);
            int digit;
            System.out.print("Enter a positive number: ");
            digit = input.nextInt();
            int power = 1;
            while (power <= digit) {
                power *= 10;
            }
            power /= 10;
            while (power > 0) {
                System.out.println(digit/power);
                digit %= power;
                power /= 10;
            }
        }
    }
    

提交回复
热议问题