Java 使用带有特定指令的数组查找数字是否可以被 11 整除的程序

Java program to find a whether a number is divisible by 11 using an array with specific instructions

嗯,它必须通过将奇数和偶数位置的数字相加来确定,如果它们相等,那么它可以被 11 整除。这必须使用数组来完成。我写了整个代码,但它不工作。谁能指出我的错误?

更正后的程序:

import java.util.*;
public class divby11
{
    public static void main(String args[])
    { 
        Scanner scan=new Scanner(System.in); //Initilize Scanner method       
        System.out.println("Enter the number:"); //Ask user for input
        int n=scan.nextInt(); //User input
        int copy=n; //Copy variable to prevent n's value being erased
        int c=0; //Count of digits
        int dig; //The digit (i.e. the last digit of n) extracted
        while(copy!=0) //Runs till the value gets 0
        {
            copy/=10; //Getting to the next number 
            c++; //Count post-fixed by 1
        }
        copy=n;
        int arr[]=new int[c]; //Fix length of array
        int i=0; //Set the increment counter; starts at 0
        while(copy!=0) //Digit extraction
        {          
            dig=copy%10; //The digit extracted
            copy/=10; //Integer division by 10 to go to next digit
            arr[i]=dig; //Set the digit to the array index
            i++; //Post-fix the increment counter
        }        
        int odd=0; //Set value
        int even=0; //Set value
        for(int j=1;j<c;j+=2) //For-loop for adding the value of the odd index nos. of the arr[] 
        { 
            odd+=arr[j]; //The sum of the series
        }           
        for(int k=0;k<c;k+=2) //For-loop for adding the values of the even index nos. of the arr[] 
        {
            even+=arr[k]; //The sum of the series
        }
        if(odd==even) //Divisible by 11
            System.out.println("The number " + n + " is divisible by 11.");
        else if(odd!=even) //Indivisible by 11
            System.out.println("The number " + n + " is not divisible by 11.");
    }  
}

这已经有反对票了。 :'(

将此处 for(int j=1;j<=c;j+=2) 和此处 for(int k=0;k<=c;c+=2) 的循环条件从 <= 更改为 <,并删除此 if(c%2==1) c++;

int i=0;
while(n!=0) //Digit extraction
    {          
           dig=n%10;
           n/=10;
           arr[i] = dig;
           i++;
    }
n=copy;

不需要嵌套循环

n值也改变了,你需要保留它以备最后打印

int odd=0;
int even=0;
for(int j=1;j<c;j+=2) //Adding odd digits
{ 
    odd+=arr[j];
}
//if(c%2==1)
//c++;
for(int k=0;k<c;k+=2) //Adding even digits
{
    even+=arr[k];
}

你的循环直到数组的一半并且

for(int k=0;k<=c;c+=2)//you incremented c instead of k