Primary Arithmetic - Source Code JAVA



Children are taught to add multi-digit numbers from right to left, one digit at a time.
Many find the “carry” operation, where a 1 is carried from one digit position to the
next, to be a significant challenge. Your job is to count the number of carry operations
for each of a set of addition problems so that educators may assess their difficulty.

Input

Each line of input contains two unsigned integers less than 10 digits. The last line of
input contains “0 0”.

Output

For each line of input except the last, compute the number of carry operations that
result from adding the two numbers and print them in the format shown below.

Sample Input

123 456
555 555
123 594
0 0

Sample Output

No carry operation.
3 carry operations.
1 carry operation.

--------------------------------------

package primaryarithmetic;
import java.util.Scanner;
/**
 *
 * @author Angie Mendez
 */
public class PrimaryArithmetic {
public static void initializeArray(int digitsA[], int digitsB[]){
    for(int i=0;i<3;i++){
    digitsA[i]=0;
    digitsB[i]=0;
    }
}
public static int convert (String input){
    int num;
    return num=Integer.parseInt(input);
}
public static void digits(int digitsA[], int digitsB[], String input){
    if(input.length()== 7){
    digitsA[0]=(convert(input.substring(0,1)));
    digitsA[1]=(convert(input.substring(1,2)));
    digitsA[2]=(convert(input.substring(2,3)));
 
    digitsB[0]=(convert(input.substring(4,5)));
    digitsB[1]=(convert(input.substring(5,6)));
    digitsB[2]=(convert(input.substring(6,7)));
    }else{
        System.exit(0);
    }
}
public static int add(int digitsA[], int digitsB[]){
    int accountant=0;
    for(int i=0;i<3;i++){
        if((digitsA[i]+digitsB[i])>=10){
            accountant++;
        }
    }
return accountant;
}
public static void check(int accountant){
    switch(accountant){
        case 0:System.out.print("No carry operation.");break;
        case 1:System.out.print(accountant + " carry operation.");break;
        case 2: case 3:System.out.print(accountant + " carry operations.");break;
    }
}
    public static void main(String[] args) {
        String input;
        int digitsA [] = new int [3];
        int digitsB [] = new int [3];
        do{
        System.out.println();
        Scanner data = new Scanner (System.in);
        input=data.nextLine();
        initializeArray(digitsA, digitsB);
        digits(digitsA, digitsB,input);
        check(add(digitsA, digitsB));
        }while(input.length()==7);
    }
}

--------------------------------------

Comentarios