Java任务:将数字转换为其他数字系统的实现方法

Java任务:将数字转换为其他数字系统的实现方法,java,Java,我的任务状况: 实现ConvertNumberTotherNumerationSystem方法的逻辑,该方法应将numbers number.getDigit从一个数字系统NumerationSystem转换为另一个预期的数字系统 如果数字不正确,则抛出NumberFormatException,例如:数字系统为2的数字120 number.getDigit验证-正整数 这是我的代码: 类解决方案 public class Solution { public static void ma

我的任务状况:

实现ConvertNumberTotherNumerationSystem方法的逻辑,该方法应将numbers number.getDigit从一个数字系统NumerationSystem转换为另一个预期的数字系统

如果数字不正确,则抛出NumberFormatException,例如:数字系统为2的数字120

number.getDigit验证-正整数

这是我的代码:

类解决方案

public class Solution {
    public static void main(String[] args) {
        Number number = new Number(NumerationSystemType._10, "6");
        Number result = convertNumberToOtherNumerationSystem(number, NumerationSystemType._2);
        System.out.println(result);    //expected 110
    }

    public static Number convertNumberToOtherNumerationSystem(Number number, NumerationSystem expectedNumerationSystem) {
        return null;
    }
枚举NumerationSystemType

public enum NumerationSystemType implements NumerationSystem {
    _16,
    _12,
    _10,
    _9,
    _8,
    _7,
    _6,
    _5,
    _4,
    _3,
    _2;

    @Override
    public int getNumerationSystemIntValue() {
        return Integer.parseInt(this.name().substring(1));
    }
}
班号

public class Number {
    private NumerationSystem numerationSystem;
    private String digit;

    public Number(NumerationSystem numerationSystem, String digit) {
        this.numerationSystem = numerationSystem;
        this.digit = digit;
    }

    public NumerationSystem getNumerationSystem() {
        return numerationSystem;
    }

    public String getDigit() {
        return digit;
    }

    @Override
    public String toString() {
        return "Number{" +
            "numerationSystem=" + numerationSystem +
            ", digit='" + digit + '\'' +
            '}';
    }
接口数字系统

public interface NumerationSystem {
    int getNumerationSystemIntValue();
}

我将非常感谢您的帮助和建议。

您需要使用源编号的计数系统来解析数字,然后使用预期的计数系统来生成新数字

public static Number convertNumberToOtherNumerationSystem(Number number, NumerationSystem expectedNumerationSystem) {
    // Get an Integer using the numeration system to parse the digits.
    int value = Integer.parseInt(number.getDigit(), number.getNumerationSystem().getNumerationSystemIntValue());
    // Convert it to new form.
    return new Number(expectedNumerationSystem, Integer.toString(value, expectedNumerationSystem.getNumerationSystemIntValue()));
}

这确实产生了110——实际上它打印了数字{numerationSystem=_2,digit='110'}。

您已经发布了需求和未解释的代码,但毫无疑问。您当前的代码有什么问题?它如何表现得不正常?你到底对什么感到困惑?请帮助我们,因为如果你不提出具体的问题,我们就不能给出具体的答案。请浏览和,特别是各部分。好吧,我读了你给我的链接。对不起,我没有提出确切的问题。