Feb 3, 2018 at 4:50 pm Java

Reading Individual digits of a Number in Java

In this post, I will show two ways of reading individual digits of a number in the Java language.
The first method is using String, and it is the easier one.

First, we change the input number to string in the following way just as we used previously to find the first digit of a number

String strInput = String.valueOf(input);

After that, we read each character using the charAt() method. Using a for loop, you can read individual characters like this


for(int i = 0; i < strInput.length(); i++){
System.out.print(strNum.charAt(i));
}

The second method doesn’t change the input to String. Instead, it prints individual digit using the modulus operator (%);

We can simply use the modulus operator to output individual digit, but the problem is the output is not as we expect it to be. In other words, we will get a reversed number.
For example, if you use the number 4356 as input, the output will be 6534. To get the correct output, we need to push each digit by 10 then the next digit by 100, etc.

In the above example, 4356%10 becomes 6. After one round of loop, the original number becomes 435 because of the number/10 statement. So 435%10 is 5. If we multiply 5 by 10 and add the result to the previous digit, it becomes 56.

Next, if we do 43%10 we get 3. Accordingly, (3 * 100) + 56 becomes 356.

Finally, (4%10 * 1000) + 356 becomes 4356 which is similar to the original number.

The full code is listed below and it contains two methods. Both methods produce similar result.


public class ReadDigits{

    //This method uses String
    public static void readNumberUsingString(int input){
	System.out.println("Your input is: " + input);
	System.out.print("Using String the output is: ");

	String strInput = String.valueOf(input);

	for(int i= 0; i < strInput.length(); i++){ 
            System.out.print(strInput.charAt(i)); 
        } //End folr loop System.out.println(); 
    }// End method 

    //This method doesn't need to use String 
    public static void readNumberWithoutString(int input){
        int output = 0; 
        int multiplier = 1; 
        System.out.println("\tAnd"); 
        System.out.print("Without using String the output is: "); 
        while(input > 0){
	     output += (input % 10) * multiplier; //multiply digit by ten to push it
	     multiplier *= 10; //increment by multiple of 10
	     input = input/10;
        } // End while loop
        System.out.println(output);
    }// End method
     
    //Main method
    public static void main(String[] args) {

	int number = 8345678;
	readNumberUsingString(number);
	readNumberWithoutString(number);

     } //End main
 } //End class

Typical output can be:
Your input is: 8345678
Using String the output is: 8345678
      And
Without using String the output is: 8345678



        

Leave a Reply

Your email address will not be published. Required fields are marked *