Domanda

Okay so I am only trying to convert a base into base 10 right now, so disregard the base_out. The while statement near the bottom is what is being problematic. I jUnitTest like this:

@Test
public void test() {
      Assert.assertEquals("0", NumberBase.convert("0000", 2, 10));
      Assert.assertEquals("1", NumberBase.convert("0001", 2, 10));
      Assert.assertEquals("2", NumberBase.convert("0010", 2, 10));
      Assert.assertEquals("3", NumberBase.convert("0011", 2, 10));
      Assert.assertEquals("4", NumberBase.convert("0100", 2, 10));
      Assert.assertEquals("5", NumberBase.convert("0101", 2, 10));
      Assert.assertEquals("6", NumberBase.convert("0110", 2, 10));
      Assert.assertEquals("7", NumberBase.convert("0111", 2, 10));
      Assert.assertEquals("8", NumberBase.convert("1000", 2, 10));

It keeps giving me the output 18 for the third test where I expect 2. I have been looking over this for a while and cannot figure out what is wrong.

public static String convert(String input, int base_in, int base_out){
    String str = "";

    for (int index = 0; index < input.length(); index++) {
        char aChar = input.charAt(index);
        sum = Character.getNumericValue(aChar);
        result.add(sum);
    }

    i = 0;
    sum = 0;
    while(i < result.size()){
        sum += (int) (result.get(result.size()-1-i))*(Math.pow(base_in, i));
        i++;

    }
    str = "" + sum;

    return str;
}
È stato utile?

Soluzione

I can only assume this happens because result appears to be a static variable that you aren't reassigning/clearing/re-initializing on each method call and therefore still holds the previous values, the sum you added on previous calls.

Either make it local to the method

public static String convert(String input, int base_in, int base_out){
    List<Integer> result = new LinkedList<>();
    ...

Or reinitialize it at the start (to clear the previous sums)

public static String convert(String input, int base_in, int base_out){
    result = new LinkedList<>(); // or just call clear()
    ...

Proof: 0000 + 0001 + 0010 = 000000010010 = 18

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top