我正在为类分配一个简单的基本转换器。我已经接近完成,但是需要整理转换算法以将用户输入的值(以给定的基数)转换为以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()方法显示它返回了预期值。假设这与所有不同的变量类型有关?我不确定
是的,你是对的,这charAt
就是问题所在。
键入“ 10”时,根据Java用于编码字符的编码表,该字符的整数值为'0'
48,而'1'
其整数值为49。
如果看一下,您会看到0被编码为0x0030 = 3*16^1 = 48
,1被编码为0x0031 = 3*16^1 + 1*16^0 = 49
依此类推。
如果要获取字符本身的数值,可以使用
numOut = Character.getNumericValue(numIn.charAt(i-1)) * Math.pow(baseIn, counter++);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句