سؤال

This is my last lab of this set for while/do-while loops and I've got it all figured out aside from my result printing out in the exact reverse of what it should be.

public class TenToAny
{
private int base10;
private int newBase;

public TenToAny()
{

}

public TenToAny(int ten, int base)
{
   base10 = ten;
   newBase = base;
}

public void setNums(int ten, int base)
{
   base10 = ten;
   newBase = base;
}
public String getNewNum()
{
    String newNum="";
    int orig = base10;

    while(orig > 0)
    {
        newNum = orig%newBase + newNum;
        orig = orig/newBase;
    }
    return newNum;
}

public String toString()
{
    String complete = base10 + " base 10 is " + getNewNum() + " in base " + newBase;

    return complete;
}


}

here's what my results should be:

234 base 10 is 280 in base 9

100 base 10 is 1100100 in base 2

these are the expect results for the first two values (234 in base 9 AND 100 in binary)

Here's what I'm getting:

234 base 10 is 082 in base 9

100 base 10 is 0010011 in base 2

هل كانت مفيدة؟

المحلول

You're simply adding the end of the newNum instead of prepending.

newNum = newNum + orig%newBase;

... should be ...

newNum = orig%newBase + newNum;

For characters...

When orig%newBase > 9, then char(55 + orig%newBase)

var nextValue = orig % newBase;

if (nextValue > 9)
{
    newNum = char(55 + nextValue) + newNum;
}
else
{
    newNum = nextValue + newNum;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top