2

背景:

我正在为班级分配制作一个简单的基本转换器。我已经接近完成,但需要整理转换算法以将用户输入的值(在给定的基数中)转换为以 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() 方法显示它返回预期值。假设它与所有不同的变量类型有关?我不确定。

4

2 回答 2

5

是的,你是对charAt的就是问题所在。

当您键入“10”时,字符的整数值为'0'48,'1'根据 Java 用于编码字符的编码表,它是 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++);
于 2015-02-11T00:37:12.687 回答
2

charAt方法返回char您输入的 ,在这种情况下'0',不是0。的 Unicode 值char '0'不是0,而是48

幸运的是,'0'through的值'9'是连续的 Unicode 值,48through57分别是,所以你可以在乘法之前48通过减法“减去”。'0'

numOut = ( (numIn.charAt(i-1) - '0') * Math.pow(baseIn, counter++));

您仍然需要验证用户键入的内容实际上是所选基数中的有效“数字”。

您还需要将 的值相numOut加以得到最后的十进制结果。

于 2015-02-11T00:37:52.987 回答