Background:
I am making a simple base converter for a class assignment. I am fairly close to completion but need to tidy up the conversion algorithm to convert the user inputted value (in a given base) to a base 10 value.
Attempt:
import java.util.Scanner;
public class BaseConverter {
public static void main(String[] args) {
String numIn, intro1, prompt1, prompt2, output1;
int baseIn;
double numOut;
boolean flag = true;
Scanner kb = new Scanner(System.in);
intro1 = "This program converts values in different number bases to a decimal value.";
prompt1 = "Type in a number base (2 - 9): ";
while (flag == true){
System.out.println(intro1);
System.out.println(prompt1);
baseIn = kb.nextInt();
//Checking base value for outliers outside given range
if (baseIn < 2 || baseIn > 9) {
System.out.println("Base must be between 2 and 9");
System.exit(1);
}
prompt2 = "Type in a base "+baseIn+" number: ";
System.out.println(prompt2);
numIn = kb.next();
// System.out.println(numStore);
int counter = 0;
// Let's pretend baseIn is 3 and i starts at 3
for (int i = numIn.length(); i >= 1; i--){
numOut = (numIn.charAt(i-1) * Math.pow(baseIn, counter++));
System.out.println(numOut);
}
}//while
}// method
}//class
The problem:
This line does not return the expected value
numOut = (numIn.charAt(i-1) * Math.pow(baseIn, counter++));
For example, in string "10", numOut should be (0*(2*0)) or zero on the first iteration of the for loop. Instead, it returns 48.0.
My Thoughts:
I have a sneaking suspicion it has to do with the charAt() method as debugging the Math.pow() method showed it returning expected values. Suppose it's something to do with all the different variable types? I'm unsure.