2016-12-20 6 views
-1

그래서 나는 자바 초보자입니다. 배열의 정수가 나에게 알려주는 프로그램을 만들려고합니다. 그러나, 나는 경계 오류에서 배열을 점점 계속 : 10 내가 "[도 [] B] 공식을 SY 29 행 (에 제발 도와주세요배열 범위 밖 예외 오류 자바

public class arrayone 
{ 
    public static void main(String args []) 
    { 
     /* 
    tell me the number of even ints in the given array. Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1. 
    */ 

    //declare an array 
    int[] even= new int[10]; 

    //int b is for the forloop so that every number can be added 
    int b; 

    // 

    //initialize the scanner, and enter prompt 
    Scanner input= new Scanner(System.in); 

    //enter prompt 
    System.out.printf("Enter 10 random numbers\n"); 

    //make a forloop so every number they put in will be added to the array 
    for(b=0;b<10;b++) 
    { 
    even[b]=input.nextInt(); 
    } 

//then run the formula 
formula(even[b]); 
    } 

    public static void formula(int a) 
    { 


     //use an if statement to see if the numbers in the array are odd or even. 
     for(a=0;a<=10;a++) 
     { 
     if((a%2)==0) 
     { 
      System.out.printf("This number is even\n"); 
     } 
     else 
     { 
      System.out.printf("This number isn't even\n"); 

     } 
     } 
    } 
} 
+2

모든 formula''에서'for' 루프가 없어야합니다. 당신은 단지'int'를 기대하고 있습니다. – Aidin

+0

나는 당신이하고 있다고 생각하는 것을 솔직하게 잃어 버렸습니다. 당신의'formula'는 전혀 이해가 안됩니다. – Aidin

+0

각 정수를 수식에 보내는 대신 왜 그렇게 전체 배열을 보내지 않으시겠습니까? https://repl.it/Eu6c/1 – shash678

답변

0
for(b=0;b<10;b++) 
    { 
     even[b]=input.nextInt(); 
    } 

을의에 대한 루프 값을 종료 한 후.? b는 배열 even의 용량보다 더 10 될 것입니다. 배열 인덱스는 0-9입니다. 따라서 예외입니다.

1

좋아, 이제

당신은 입력의 무리를 읽고 저장할 처음부터 시작하자 배열로, 지금까지 그렇게 좋은.

그러면 을 수행하여 formula 함수에 하나의 값만 보내려고합니다. 그러나 @Sanjeev가 지적한대로 b = 10은 바로 전에 for 루프 때문에이 순간에 array out of bounds을 제공합니다.

그리고 formula 당신이 단지 int을 기대하지만 (귀하의 경우 a)이 int을 그냥 BTW 0 (포함) 10 사이의 숫자도 무엇인지 확인하는 for 루프를 재 할당

. 네가 원했던게 아니야.

은 당신이 정말로 원하는 것은 다음 중 하나

for(int i = 0; i < 10; i++) { 
    formula(even[i]); 
} 

public static void formula(int a) 
{ 
    if((a%2)==0) 
    { 
     System.out.printf("This number is even\n"); 
    } 
    else 
    { 
     System.out.printf("This number isn't even\n"); 
    } 
} 

또는

formula(even); 

public static void formula(int[] a) 
{ 
    for(int i = 0; i < a.length(); i++) { 
     if((a[i]%2)==0) 
     { 
      System.out.printf("This number is even\n"); 
     } 
     else 
     { 
      System.out.printf("This number isn't even\n"); 
     } 
    } 
} 
+0

중복 된 것으로 표시된 후에 어떻게 대답 했습니까? – shash678

+1

아마 신고 할 때 이미 답변을하고 있다고 생각합니다. – Aidin