#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2013
    Posts
    1
    Rep Power
    0

    Fun with integers!




    http://imgur.com/6RZcKU6 check this for the programming problem

    A friend of mine is taking C in school and he sends me over programming problems he gets so I can give it a shot in Java. I am not sure how to do this one?

    Here is what i have come up with:

    Code:
    package com.practiceApp;  
    import java.util.Scanner;   
    public class Main 
    {  	public static void main(String[] args) 
    {  		
    System.out.println("Enter a number: ");  		
    Scanner in = new Scanner(System.in); 		
    int userNum = in.nextInt(); 		 		
    int r = 1; 		
    while (10 * r < userNum) 		
    { 			
    int result = userNum % r; 			
    r *= 10; 			
    System.out.println(result); 		
    } 		 		
    in.close();  
    }  
    }
    A few issues:

    So, for input value "101", the output should be:

    101
    01
    1

    as opposed to:

    101
    1

    Anyone know how to do this with integers using math that would be awesome. I know you can do this using strings.

    Thanks!
  2. #2
  3. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jan 2004
    Location
    Mobile, Alabama
    Posts
    4,021
    Rep Power
    1285
    One approach I could suggest is to start with your original number, and remove the digits from it one by one using the % and / operators. When you take the digits out of the number, place them into a new new. The number of digits you add to the new number will depend on which line you are printing. After you have your new number, you would have to add a String with a certain amount of spaces in it when you print it.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2013
    Posts
    1
    Rep Power
    0
    try this one
    Code:
    import java.util.*;//for Scanner
    import java.lang.*;//for Math.pow(double,double)
    class myclass{
    
    public static void main(String[] args)
     {
     Scanner sc=new Scanner(System.in);
     System.out.println("enter a number");
     int num =sc.nextInt();
    
     int numOfDigits=0;//holds number of digits
     int temp=num;//holds copy of num  for temporarily
    
     //calculate number of digits in entered number
     while(temp>0)
      {
      temp=temp/10;
      numOfDigits++;
      }
    
     numOfDigits--;//if number of digits is 3 then decrement it by 2
    
     while(numOfDigits>0)
      {
      num=num%((int)Math.pow(10,numOfDigits)); 
      System.out.println(num);
      numOfDigits--;
      }
    
     }//main() ends
    
    }//myclass ends

IMN logo majestic logo threadwatch logo seochat tools logo