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

前端 未结 10 659
忘了有多久
忘了有多久 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:17

    I also just started with java and with this book, and this is the code that did the tric for me. Forgive me if i did something strange... :)

    import java.util.Scanner;
    
    public class SeparateNumber
    {
        public static void main(String[] args)
        {
            Scanner in = new Scanner(System.in);
            int nr, nr1, nr2, nr3, nr4, nr5;
    
            System.out.print("Enter a number with 5 digits: ");
            nr = in.nextInt();
    
            nr1 = nr / 10000;
            nr2 = (nr % 10000) / 1000;
            nr3 = ((nr % 10000) % 1000) / 100;
            nr4 = (((nr % 10000) % 1000) % 100) / 10;
            nr5 = (((nr % 10000) % 1000) % 100) % 10;
    
            System.out.printf("%d%s%d%s%d%s%d%s%d%n", nr1, " ", nr2, " ", nr3, " ", nr4, " ", nr5);
        }
    }
    

提交回复
热议问题