I have written a Java program that converts an integer to String digit by digit and concatenate them together using the + operator without touching the Stock Java API library.
I like to have feedback on my code. Where do I need to improve. If I need to deduct something. So please criticize me. Thank you.
import java.util.Scanner;
public class StrFromInteger {
/*
* a single digit is passed as an argument
* And a matching digit of String type
* is returned.
*/
public static String returnDigitString(int digit) {
String res = "";
switch(digit) {
case 0:
res = "0"; break;
case 1:
res = "1"; break;
case 2:
res = "2"; break;
case 3:
res = "3"; break;
case 4:
res = "4"; break;
case 5:
res = "5"; break;
case 6:
res = "6"; break;
case 7:
res = "7"; break;
case 8:
res = "8"; break;
case 9:
res = "9"; break;
}
return res;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//Scan the integer as int
Scanner scn = new Scanner(System.in);
int number = scn.nextInt();
//find the number of digits using logarithm
//if input number is not equal to zero because
//log of zero is undefined otherwise if input
// number zero length is equal to 1
int input = number;
int length = 0;
if(number != 0) {
length = ( int ) (Math.log10(number) + 1 );}
else if(number ==0) {
length = 1;
}
//Save each digit in String format by passing
// the integer digit to the returnDigitString()
//method one by one
String[] reverseStr = new String[length];
String digits = "0123456789";
int remainder =0;
int result = number ;
--length;
number = length;
String strSeq = "";
String valStr = "";
// loop through the whole integer digit by digit
//use modulo operator get the remainder
//save it in remainder. then concatenate valStr
//returned from returnDigitString()
//method with previous String of Digits. Divide the result by 10. Again
//repeat the same process. this time the modulo and the
//number to be divided will be one digit less at each decremental
//iteration of the loop.
for(int i = number; i >= 0; --i) {
remainder = result % 10;
valStr = returnDigitString(remainder);
strSeq = valStr + strSeq;
result = result / 10;
}
//Print the string version of the integer
System.out.println("The String conversion of " + input + " is: " + strSeq);
}
}