背景:
我正在为班级分配制作一个简单的基本转换器。我已经接近完成,但需要整理转换算法以将用户输入的值(在给定的基数中)转换为以 10 为基数的值。
试图:
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
问题:
此行不返回预期值
numOut = (numIn.charAt(i-1) * Math.pow(baseIn, counter++));
例如,在字符串“10”中,在 for 循环的第一次迭代中,numOut 应该是 (0*(2*0)) 或零。相反,它返回 48.0。
我的想法:
我偷偷怀疑它与 charAt() 方法有关,因为调试 Math.pow() 方法显示它返回预期值。假设它与所有不同的变量类型有关?我不确定。