Java Character to Integer Example, use Character.getNumericValue() or digit()

                           In this tutorial, let us see how to convert character (digit as character)  to integer in different ways with example. Some times, there may be a situation where you need to convert a character to integer. For example, consider the program to calculate sum of the digits of a number. In that, you are accepting a number as a string, and calculate sum of all digits of the number. One way to do this is to convert the string into integer, then split individual digits of the integer and add. Another way to do this is, to split each character from string, then convert each character to integer and add. Let us go through the second way to explain character to integer conversion.

                There are many ways to convert the character to integer. One way is to use Character class. You can use either Character.getNumericValue(char) or Character.digit(char,10) or use the below lines.

                                         Character temp=new Character(char),

                                         Integer.parseInt(temp.toString()).

The following code calculates the sum of digit of number using the character to integer */

package net.javaonline;

import java.util.Scanner;

class CharacterToInteger {

	public static void main(String[] args) {

		Scanner input = new Scanner(System.in);

		System.out.println("Please enter any number ");

		String numStr = input.next();

		long sod = sumofdigit(numStr);

		System.out.println("Sum of digits of  " + numStr + " is " + sod);

	}

	// The sumofdigit function which calculates sum of digits.

	public static long sumofdigit(String numStr)

	{

		long sod = 0;

		for (int i = 0; i <= numStr.length() - 1; i++) {

			int digit = chartoInt(numStr.charAt(i)); // using
														// getNumericValue(char)

			// int digit =chartoInt2(numStr.charAt(i)); //using toString() &amp;
			// parseInt()

			// int digit =chartoInt3(numStr.charAt(i)); // using digit(char,10)

			sod += digit;

		}

		return sod;

	}

	public static int chartoInt(char c)

	{

		return Character.getNumericValue(c);

	}

	public static int chartoInt2(char c)

	{

		Character temp = new Character(c);

		return Integer.parseInt(temp.toString());

	}

	public static int chartoInt3(char c)

	{

		return Character.digit(c, 10);

	}

}

Run the program

character to integer

 

 

You may also like

Leave a Reply

Be the First to Comment!