How to get one digit per line...please help, beginner :(

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • lifeshortlivitup
    New Member
    • Sep 2006
    • 16

    How to get one digit per line...please help, beginner :(

    Hello all....I am brand new to this whole Java environment and have become stumped with an early homework assignment. It sounds simple enough, but after hours and hours of working on it I can't get it to give me the correct output. The problem calls for me to enter a four digit number and the number then needs to be output one digit per line like so:

    1
    9
    9
    1

    Anyone have any ideas? Thanks!
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    A-hah! This is a classic problem, and it's been made so much easier by knowing that the number is a four digit number.

    Consider the following statements (Please excuse any syntax errors - it's been a while since I did any Java, as I've been learning C++):

    Code:
    public class theClass {
       public static void main(string[] args) {
          int num;
          // Get user input stored into num here (I've forgotten how to do this)
          // Suppose the user enters 1991, as in your example.  Then num == 1991.
    Now, how do we get the thousands place? We can't treat num as a string and get substrings - but we can use math! Using integer division, what is 1991 / 1000? The answer is 1 - the digit we needed!

    So now we've got a way to find the first digit - now what? You might think we divide 1991 by 100 - but this gives us 19, not 9. We need to change num somehow - get rid of the 1000, so to speak. The answer is using modulus division - 1991 % 1000 gives us 991. Then we can divide by 100 to get 9 - the second digit!

    Repeating this until you get all 4 digits will give you code like this:

    Code:
    public class theClass {
       public static void main(string[] args) {
          int num;
          // Get user input stored into num here (I've forgotten how to do this)
          // Suppose the user enters 1991, as in your example.  Then num == 1991.
          System.out.println(num / 1000);
          num = num % 1000;   // This could be shortened to num%= 1000;
          System.out.println(num / 100);
          num = num % 100;
          System.out.println(num / 10);
          num = num % 10;
          System.out.println(num / 1); // note: this is the same as System.out.println(num);
       }
    }
    Now, a true problem to challenge you would be: how do you do the same thing without knowing the length of the integer?

    Comment

    • r035198x
      MVP
      • Sep 2006
      • 13225

      #3
      Originally posted by Ganon11
      A-hah! This is a classic problem, and it's been made so much easier by knowing that the number is a four digit number.

      Consider the following statements (Please excuse any syntax errors - it's been a while since I did any Java, as I've been learning C++):

      Code:
      public class theClass {
         public static void main(string[] args) {
            int num;
            // Get user input stored into num here (I've forgotten how to do this)
            // Suppose the user enters 1991, as in your example.  Then num == 1991.
      Now, how do we get the thousands place? We can't treat num as a string and get substrings - but we can use math! Using integer division, what is 1991 / 1000? The answer is 1 - the digit we needed!

      So now we've got a way to find the first digit - now what? You might think we divide 1991 by 100 - but this gives us 19, not 9. We need to change num somehow - get rid of the 1000, so to speak. The answer is using modulus division - 1991 % 1000 gives us 991. Then we can divide by 100 to get 9 - the second digit!

      Repeating this until you get all 4 digits will give you code like this:

      Code:
      public class theClass {
         public static void main(string[] args) {
            int num;
            // Get user input stored into num here (I've forgotten how to do this)
            // Suppose the user enters 1991, as in your example.  Then num == 1991.
            System.out.println(num / 1000);
            num = num % 1000;   // This could be shortened to num%= 1000;
            System.out.println(num / 100);
            num = num % 100;
            System.out.println(num / 10);
            num = num % 10;
            System.out.println(num / 1); // note: this is the same as System.out.println(num);
         }
      }
      Now, a true problem to challenge you would be: how do you do the same thing without knowing the length of the integer?
      And what if I may ask is wrong with

      Code:
      import java.util.Scanner;
      public class theClass {
         public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            System.out.print("Enter the number: ");
            int num = scan.nextInt();
            String s = ""+num;
      
            for(int i = 0; i < s.length(); i++) {
                System.out.println(s.charAt(i));
            }
         }
      }

      Comment

      • Ganon11
        Recognized Expert Specialist
        • Oct 2006
        • 3651

        #4
        Absolutely nothing! Indeed, this accomplishes the task perfectly well. However, whenever I received this problem (or similar ones) in my programming class, we were prevented from using string functions - we had to keep num as an integer and nothing else. Thus, I developed the solution above. Both work equally well.

        Comment

        • r035198x
          MVP
          • Sep 2006
          • 13225

          #5
          Originally posted by Ganon11
          Absolutely nothing! Indeed, this accomplishes the task perfectly well. However, whenever I received this problem (or similar ones) in my programming class, we were prevented from using string functions - we had to keep num as an integer and nothing else. Thus, I developed the solution above. Both work equally well.
          I see what the fuss is about now. Do you have the solution for unknown number length

          Comment

          • Ganon11
            Recognized Expert Specialist
            • Oct 2006
            • 3651

            #6
            Indeed I do. There were two different problems I had to do for an unknown length number; printing the digits in reverse order and in regular order. I'll start with reverse order.

            The concept is actually reversed for this - using mod to retrieve the digits and dividing to update the number. The entire thing is controlled by a while loop, as follows:

            Code:
            // Assume num is some integer of unknown length
            while (num > 10) {
               int digit = num % 10;
               num /= 10;
               System.out.print(digit + " ");
            }
            System.out.println(num);
            While number has 2 or more digits (a.k.a. larger than 10), I retrieve the first digit by modding by 10. Then I divide the number by 10 to delete the first digit. because this is integer division, there is no messy decimal to work with (a.k.a. 1234 / 10 = 123, not 123.4). I repeat this until there is only 1 digit left, then print that last digit - the number itself!

            Printing the digits in order is a bit trickier. While there is likely a more concise / effecient way to do this, I only knew how to print digits backwards - thus, I took num and reversed the digits into newNum, then applied the same process to newNum. The code looks like:

            Code:
            //Assume num is some integer of unknown length
            int newNum = 0;
            while (num > 10) {
               newNum += num % 10;
               newNum *= 10;
               num /= 10;
            }
            newNum += num;
            
            while (newNum > 10) {
               int digit = newNum % 10;
               newNum /= 10;
               System.out.print(digit + " ");
            }
            System.out.println(newNum);
            The first while loop sets newNum to num, but reversed, by getting the first digit of num, adding it to newNum, then multiplying newNum by 10 (If num was 123, then after one iteration, newNum would be 30 and num would be 12). This happens until num is one digit long - I then add it to newNum as the last digit. Then I print the digits of newNum in reverse order the same way as the first problem.

            One disadvantage I have realized, however, occurs when the user enters an integer ending with 0 (such as 1960). Then 1 9 6 will be printed, not 1960.

            Any idea how to solve, without using string functions?

            Comment

            • r035198x
              MVP
              • Sep 2006
              • 13225

              #7
              Originally posted by Ganon11
              Indeed I do. There were two different problems I had to do for an unknown length number; printing the digits in reverse order and in regular order. I'll start with reverse order.

              The concept is actually reversed for this - using mod to retrieve the digits and dividing to update the number. The entire thing is controlled by a while loop, as follows:

              Code:
              // Assume num is some integer of unknown length
              while (num > 10) {
                 int digit = num % 10;
                 num /= 10;
                 System.out.print(digit + " ");
              }
              System.out.println(num);
              While number has 2 or more digits (a.k.a. larger than 10), I retrieve the first digit by modding by 10. Then I divide the number by 10 to delete the first digit. because this is integer division, there is no messy decimal to work with (a.k.a. 1234 / 10 = 123, not 123.4). I repeat this until there is only 1 digit left, then print that last digit - the number itself!

              Printing the digits in order is a bit trickier. While there is likely a more concise / effecient way to do this, I only knew how to print digits backwards - thus, I took num and reversed the digits into newNum, then applied the same process to newNum. The code looks like:

              Code:
              //Assume num is some integer of unknown length
              int newNum = 0;
              while (num > 10) {
                 newNum += num % 10;
                 newNum *= 10;
                 num /= 10;
              }
              newNum += num;
              
              while (newNum > 10) {
                 int digit = newNum % 10;
                 newNum /= 10;
                 System.out.print(digit + " ");
              }
              System.out.println(newNum);
              The first while loop sets newNum to num, but reversed, by getting the first digit of num, adding it to newNum, then multiplying newNum by 10 (If num was 123, then after one iteration, newNum would be 30 and num would be 12). This happens until num is one digit long - I then add it to newNum as the last digit. Then I print the digits of newNum in reverse order the same way as the first problem.

              One disadvantage I have realized, however, occurs when the user enters an integer ending with 0 (such as 1960). Then 1 9 6 will be printed, not 1960.

              Any idea how to solve, without using string functions?
              If the number ends with a zero, the first num % 10 always gives zero. You can use that to determine whether or not you print a zero at the end.

              Comment

              • Ganon11
                Recognized Expert Specialist
                • Oct 2006
                • 3651

                #8
                Originally posted by r035198x
                If the number ends with a zero, the first num % 10 always gives zero. You can use that to determine whether or not you print a zero at the end.
                True. The resulting code would then be:

                Code:
                //Assume num is some integer of unknown length
                bool hasAZero = (num % 10 == 0); // New line here - checks if first digit is 0
                int newNum = 0;
                while (num > 10) {
                   newNum += num % 10;
                   newNum *= 10;
                   num /= 10;
                }
                newNum += num;
                
                if (hasAZero) System.out.print("0 "); // New line here - prints a 0 if first digit was 0
                while (newNum > 10) {
                   int digit = newNum % 10;
                   newNum /= 10;
                   System.out.print(digit + " ");
                }
                System.out.println(newNum);

                Comment

                • r035198x
                  MVP
                  • Sep 2006
                  • 13225

                  #9
                  Originally posted by Ganon11
                  True. The resulting code would then be:

                  Code:
                  //Assume num is some integer of unknown length
                  bool hasAZero = (num % 10 == 0); // New line here - checks if first digit is 0
                  int newNum = 0;
                  while (num > 10) {
                     newNum += num % 10;
                     newNum *= 10;
                     num /= 10;
                  }
                  newNum += num;
                  
                  if (hasAZero) System.out.print("0 "); // New line here - prints a 0 if first digit was 0
                  while (newNum > 10) {
                     int digit = newNum % 10;
                     newNum /= 10;
                     System.out.print(digit + " ");
                  }
                  System.out.println(newNum);
                  You are certainly having a nice time with c++, java syntax mixups!

                  Comment

                  • Trielectra3
                    New Member
                    • Sep 2015
                    • 1

                    #10
                    how does this program work exactly to get the output?

                    Comment

                    • chaarmann
                      Recognized Expert Contributor
                      • Nov 2007
                      • 785

                      #11
                      And if you have 2 or more zeros at the end, like "1230000", then your reverse loop trick won't work, even if you remember the first zero. It would print "1230"

                      So my suggestion:
                      Remember the number of all zeros by counting them in the first loop.

                      Or do a different approach:
                      First determine the length of the number and then use your first algorithm that prints them left to right.

                      You can determine the length of the number n in different ways.
                      For example:
                      "int length = (int)(Math.log1 0(n)+1);".

                      So you can start with a modulo operator of 10 power of length.
                      Now make a loop from i=length down to 0 and print one digit in each step.

                      Comment

                      • ishaandhaddha
                        New Member
                        • Dec 2015
                        • 1

                        #12
                        try this bro
                        Code:
                        import java.util.Scanner;
                        
                        class digitfinder
                        {
                            public static void main()
                           {
                                Scanner sc=new Scanner(System.in);
                                System.out.println("Enter the number");
                                int num;
                                System.out.println("Enter the digit");
                                int digit;
                                num = sc.nextInt();
                                int z=0;
                                int x=0;
                                int y;//y=56=num
                                y=num;
                                int rem=0;
                              while (y != 0) 
                              {
                                x=y%10;
                                z=z+x;
                                y=y/10; 
                                System.out.println(x);
                                
                              }
                           z=z-x;
                           System.out.println(x);
                           System.out.println(z);
                            }
                        }
                        Last edited by Rabbit; Dec 25 '15, 05:34 PM. Reason: Please use [code] and [/code] tags when posting code or formatted data.

                        Comment

                        • dabuoy
                          New Member
                          • Jan 2016
                          • 1

                          #13
                          This the way it works, you have to use a loop structure because the program does not know how many numbers is the user going to input.

                          Sample:

                          Code:
                          import java.util.Scanner; 
                          
                          public class Digit_Display 
                          { 
                          public static void main(String[] args) 
                          { 
                          Scanner scan = new Scanner(System.in); 
                          
                          int input = 0; //Stores the input from the user 
                          String inputAsString = ""; //Stores input as a string 
                          
                          //Prompts the user to enter the integer 
                          System.out.print("Enter a positive integer: "); 
                          input = scan.nextInt(); 
                          
                          //Determine if input is a positive integer. If not, prompt the user to re-enter 
                          //a positive integer 
                          if(input < 0) 
                          { 
                          System.out.print("The integer given is not positive. Please re-enter another" 
                          + " integer: "); 
                          input = scan.nextInt(); 
                          } 
                          
                          inputAsString = Integer.toString(input); 
                          
                          System.out.println(); 
                          
                          //Displays each digit of the integer on separate lines 
                          for(int count = 0; count < inputAsString.length(); 
                          count++) 
                          { 
                          System.out.println(inputAsString. 
                          charAt(count)); 
                          } 
                          } 
                          }
                          Last edited by Rabbit; Jan 26 '16, 11:35 PM. Reason: Reason: Please use [code] and [/code] tags when posting code or formatted data.

                          Comment

                          Working...