0
對於我的程序,我試圖將數字從一個基地轉換爲另一個基地。然而,我想弄清楚爲什麼我不斷收到ArrayOutOfBoundsException。誰能幫忙?我使用21作爲數字,10作爲原始基數,然後2作爲新基數。ArrayOutOfBoundsException與基地轉換
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
//Enter original number
System.out.println("Enter a number: ");
Double num = input.nextDouble();
String orgNum = String.valueOf(num);
//Enter original base
System.out.println("Enter its base: ");
int b = input.nextInt();
//Enter new base
System.out.println("Enter base to be converted to: ");
int a = input.nextInt();
input.close();
//Conversion
String newNum = convertBase(orgNum, b, a);
//New number
System.out.println("New Number: " + newNum);
}
public static String convertBase(String orgNum, int b, int a)
{
double value = 0;
double decDigit = 0;
char chDigit;
int length = orgNum.length();
for (int p = 0; p < length; p ++)
{
chDigit = Character.toUpperCase(orgNum.charAt(length - 1 - p));
if(Character.isLetter(chDigit))
{
decDigit = chDigit - 'A' + 10;
}
else if (Character.isDigit(chDigit))
{
decDigit = chDigit - '0';
}
else
{
System.out.println("ERROR: Digit is unrecognizable.");
}
value += decDigit + Math.pow(b, p);
}
int D = 1;
for (D = 1; Math.pow(a, D) <= value; D++) {}
char[] newNum = new char[D];
double pwr;
for (int p = D - 1; p >= 0; D--)
{
pwr = Math.pow(a, p);
decDigit = Math.floor(value/pwr);
value -= decDigit*pwr;
if (decDigit <= 9)
{
newNum[D - 1 - p] = (char) ('0' + (int)decDigit);
}
else
{
newNum[D - 1 - p] = (char) ('0' + (int)decDigit - 10);
}
}
return new String(newNum);
}
您可以在代碼中添加註釋以獲取異常嗎? – kolonel 2014-10-27 00:00:50
for(int p = D - 1; p> = 0; D--)這看起來很腥。不應該是(int p = D - 1; p> = 0; p--)? – Oncaphillis 2014-10-27 00:07:50