Code points
While char
can be made to work for you, that is a legacy data type. As a 16-bit value, char
is physically incapable of representing most characters.
So I suggest you make a habit of using code point integer numbers when working with individual characters.
int[] codePoints = "1234".codePoints().toArray() ;
Loop each code point. Test if that code point represents a character that is a digit. Change each code point back to text. Parse that text as an integer. Multiply using Math.multiplyExact
to alert us to integer overflow. Finally, report result.
int multiplicand = 2 ;
for( int codePoint : codePoints )
{
if( Character.isDigit( codePoint ) )
{
String digitAsText = Character.toString( codePoint ) ;
int x = Integer.parseInt( digitAsText ) ;
int y = Math.multiplyExact( x , multiplicand ) ;
System.out.println( x + " * " + multiplicand + " = " + y) ;
}
}
See this code run at Ideone.com.
1 * 2 = 2
2 * 2 = 4
3 * 2 = 6
4 * 2 = 8
Shorter code
I am a beginner and I will try to write my problem as short as possible;
Short code is rarely a wise goal.
Longer code, written with short simple statements, is easier to read, easier to debug, and easier for the compiler to optimize.
But if you insist, here is a single statement that leverages advanced features of Java including streams, lambdas, and method references.
"1234"
.codePoints()
.filter( Character :: isDigit )
.mapToObj( Character :: toString )
.map( Integer :: valueOf )
.map( ( Integer integer ) -> Math.multiplyExact( integer , 2 ) )
.forEach( System.out :: println );
This single-statement code involves auto-boxing. So this code may run a tiny bit slower than the longer code above.
When run:
2
4
6
8