I am relatively new to coding and could use some help figuring out how I could improve my coding technique and habits. Here's an example of a working Java program I wrote that converts a number of some radix (from 2 to 36) to another radix (from 2 to 36).
Any tips or criticisms?
class RadixConverter {
// command line arguments: (number) (radix of number) (radix to be converted to)
public static void main(String[] args) {
String n = args[0]; // n kept as String to support alphabetic representations of numerals for larger radixes
int startRadix = Integer.parseInt(args[1]);
int endRadix = Integer.parseInt(args[2]);
int decimal = convertToDecimal(n, startRadix);
String result = convertToBase(decimal, endRadix);
System.out.printf("%s (%d) = %s (%d)%n", n, startRadix, result, endRadix);
}
public static int convertToDecimal(String n, int startRadix) {
int sum = 0;
for (int i = 0; i < n.length(); i++) { // begins at first digit and ends at last digit
char digit = n.charAt(i);
int placeValue = (int) Math.pow(startRadix, n.length() - i - 1); // place value of digit's column
if ((digit >= 48) && (digit <= 57) && (digit - 48 < startRadix)) { // if digit is numerical and is within specified radix
sum += (digit - 48) * placeValue;
} else if ((digit >= 65) && (digit <= 90) && (digit - 65 + 10 < startRadix)) { // if digit is alphabetic and within specified radix
sum += (digit - 55) * placeValue;
} else {
throw new IllegalArgumentException("\n\nThe input number is invalid or contains digits outside of its specified radix.\n");
}
}
return sum;
}
public static String convertToBase(int decimal, int endRadix) {
StringBuilder sb = new StringBuilder("");
do {
int rem = decimal % endRadix;
if ((rem <= 9) && (endRadix <= 36) && (endRadix >= 2)) {
sb.append(Integer.toString(rem));
} else if ((rem <= 35) && (endRadix <= 36) && (endRadix >= 2)) {
sb.append((char) (rem + 55));
} else {
throw new IllegalArgumentException("\n\nThe output radix must be from 2 to 36.\n");
}
decimal /= endRadix;
} while (decimal != 0);
return reverseOrder(sb.toString());
}
public static String reverseOrder(String s) {
StringBuilder sb = new StringBuilder("");
for (int i = s.length() - 1; i >= 0; i--) { // executes each character in reverse order
sb.append(s.charAt(i));
}
return sb.toString();
}
}