簡體   English   中英

Java代碼中的編譯錯誤(找不到符號)

[英]Compilation error in Java code (cannot find symbol)

我已經更改了很多代碼。 對於以前不清楚的事情,我深表歉意。 我需要找到數組中奇數索引位置的整數之和。 我已經將代碼修改為:

  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);
       }
     }

輸出應該是30,但我收到50。不確定代碼中的錯誤在哪里。

編輯

畢竟我已經自己修好了。 參見下面的答案。 感謝大家的寶貴意見!

您不必使用奇數數組。 首先,您甚至都沒有導入oddArray。 您不能使用它。 您的問題確實令人困惑。 我假設您想知道數組中的哪些元素是奇數,然后是它們的總和。

    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);
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM