简体   繁体   中英

Compilation error in Java code (cannot find symbol)

I've changed my code quite a bit. I apologize for not being more clear before. I need to find the sum of ints at the odd index positions within an array. I've modified my code to this:

  public class OddIndex 
   {
     public static void main(String[] args) 
      {
        int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        OddIndex arr = new OddIndex();
        int sum = 0;

        for (int i = 0 ; i < numbers.length; i++) 
         {
           if ((i%2!=0))
            {
              sum += Integer.parseInt(String.valueOf(numbers.length));              
            }
         }

         System.out.println(sum);
       }
     }

The output should be 30, but I'm receiving 50. Not sure where the error exists within the code.

EDIT

I've fixed it myself after all. See below for answer. I appreciate the input from everyone!

You don't have to use oddarray. First of all you haven't even imported oddArray. You cannot use it. Your question is really confusing. Im assuming you want to know which elements in your array are odd and then their sum.

    public class OddArrayClient
    {
     public static void main( String[] args)
     {

       int [] intEle = {25, 2, 6, 86, 2, 9};

       int sum=0;
       System.out.print( "The odd elements of the array are: " );


       for (int i = 0; i < intEle.length; i++)
       {

         if (intEle[i]%2 !=0)
         {
         System.out.print(intEle[i] + " ");
         sum=sum+intEle[i];        
         }
       }


      System.out.println();

      System.out.println("The product of all odd elements is: "+sum);  
 }

}

问题是您尚未定义或导入OddArray

public class OddArrayClient
{
  public static void main( String [] args )
   {
    int [] sampleArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    int sum=0;


    for ( int i = 0; i < sampleArray.length; i++ )
    {
      if (i%2 != 0)
      {
        sum=sum+sampleArray[i];
      }
    }

    System.out.print( "The sum of odd elements of the array is : " +sum);
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM