我寫了下面的程序以相反的順序打印一個數字。 這是給我一個ArrayIndexOutOfBound例外我寫了一個程序以相反的順序打印一個數字的數字。它給我ArrayIndexOutOfBound異常
import java.util.Scanner;
public class Ch6_26 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int x;
System.out.println("Enter the number to be reversed: ");
x = input.nextInt();
Reverse(x);
}
static void Reverse(int a){
int s[] = new int[5];
int j = 0;
int x = a;
for(int i = 1; a >= 0 ; i++){
s[i] = x % 10;
x /= 10;
j = i;
}
for(int i = 0; i <= j; i++){
System.out.printf("%d ", s[i]);
}
}
}
爲什麼s []做成int [5]?什麼是最大的x將會是?爲什麼我從1開始不是0? 'j'真的是這個變量的好名字嗎? – DarenW
你的for循環看起來好像會永遠運行一樣,因爲它正在檢查a> = 0,並且a在循環中根本沒有改變。 –
而...你應該調試。這意味着你正在訪問一個超出數組邊界的索引。 –