내림차순으로 1-9까지 큐브를 사용하는 for 루프에서 배열을 사용하는 데 어려움을 겪고 있습니다. 나는 한계 밖의 오류를 계속해서 얻고 세제곱 값은 완전히 벗어났다. 배열에 대해 생각할 때 잘못된 부분에 대해 설명해 주시면 감사하겠습니다. 문제는 내 색인과 관련이 있다고 생각하지만 이유를 설명하기 위해 애 쓰고 있습니다.For Loop in Array (Java) 인덱스 범위 초과
System.out.println("***** Step 1: Using a for loop, an array, and the Math Class to get the cubes from 9-1 *****");
System.out.println();
// Create array
int[] values = new int[11];
int[] moreValues = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Create variable to store cubed numbers
double cubedNumber = 0;
// Create for loop to count in descending order
for (int counter = 9; counter < moreValues.length; counter--)
{
cubedNumber = Math.pow(counter,3);
System.out.println(moreValues[counter] + " cubed is " + cubedNumber);
}
즉시 counter' -1에 도달', 그것은 시도하고 범위를 벗어 따라서, 존재하지 않는 인덱스 배열의 값을 읽습니다. 'for (int counter = (moreValues.length) -1; counter> = 0; counter -)'와 함께 더 나을 수도 있습니다. (왜 당신이 당신의 경우에 대신 카운트 다운을하길 원하는지는 저 밖에 있습니다. – AntonH
'수학'줄에서 'moreValues [카운터]'가 아니라 카운터를 큐브하는 걸 깨닫습니까? –
체크 아웃 할 가치가 있지만 중복되지는 않습니다. https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it – AntonH