Write a Java program that reads an positive integer and count the number of digits


Introduction

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..


techstudy.org

Kindle Paperwhite High Resolution Display Tablet | Rs. 9999

  1. import java.util.Scanner;
  2. public class JavaExcercise {
  3.  
  4. public static void main(String[] args)
  5. {
  6. Scanner in = new Scanner(System.in);
  7. System.out.print("Enter any number: ");
  8.  
  9. if (in.hasNextLong())
  10. {
  11.  
  12. long num = in.nextLong();
  13.  
  14. if (num < 0)
  15. {
  16. num *= -1;
  17. }
  18. {
  19. int digits = 1;
  20. if (num >= 10 && num < 100)
  21. {
  22. digits = 2;
  23. }
  24. else if (num >= 100 && num < 1000)
  25. {
  26. digits = 3;
  27. }
  28. else if (num >= 1000 && num < 10000)
  29. {
  30. digits = 4;
  31. }
  32. else if (num >= 10000 && num < 100000)
  33. {
  34. digits = 5;
  35. }
  36. else if (num >= 100000 && num < 1000000)
  37. {
  38. digits = 6;
  39. }
  40. else if (num >= 1000000 && num < 10000000)
  41. {
  42. digits = 7;
  43. }
  44. else if (num >= 10000000 && num < 100000000)
  45. {
  46. digits = 8;
  47. }
  48. else if (num >= 100000000 && num < 1000000000)
  49. {
  50. digits = 9;
  51. }
  52. else if (num >= 1000000000 && num < 10000000000L)
  53. {
  54. digits = 10;
  55. }
  56. System.out.println("Number of digits in the number: " + digits);
  57. }
  58. }
  59. else
  60. {
  61. System.out.println("The number is not an integer");
  62. }
  63. }
  64. }

Result

java techstudy.org

     





Related Topics


Responses




Popular Posts

Facebook

Founded in 2016, Tech Study passionately delivers stylish and dynamic innovative information to programmer and technology lovers. http://www.techstudy.org/.