'Adding two numbers stored as arrays of chars

I'm trying to write an algorithm which adds two numbers that are stored as chars in two arrays. Unfortunately, it doesn't work. When I try to debug it, I see that the variables a and b get the value -1 which makes no sense. Any idea what might be the problem?

public class rechner2 {

    public static void main(String[] args) {
        final char[] zahl1 = {1, 2, 3};
        final char[] zahl2 = {7, 8, 9};
        
        //Add arrays zahl1 and zahl2.
        char [] zwischenarray = add(zahl1, zahl2);
        for (int i = 0; i < zwischenarray.length; i++) {
            System.out.println(zwischenarray[i]);
        }
    }
    

    private static char[] add(char[] zahl1, char[] zahl2) {
        int len;
        if (zahl1.length < zahl2.length) {
            len = zahl2.length;
        } else {
            len = zahl1.length;
        }
            
        char[] finalresult = new char [len + 1];
        int carryover = 0;
        
        for (int i = 0; i < len; i++) {
            int a = Character.getNumericValue(zahl1[i]);            
            int b = Character.getNumericValue(zahl2[i]);
            int c = a + b + carryover;
            if (c > 9) {
                carryover = 1;
                c = c - 10;
            } else {
                carryover = 0;
            }
            finalresult[i] = (char)c;
        }
        
        if (carryover == 1) {
            finalresult[len + 1] = 1;
        }
        
        return finalresult;
    }
}


Solution 1:[1]

in this code I believe 2 bug

  1. instead of char , i guess better to us int
  2. length of the array

here is the code: public class rechner2 {

public static void main(String[] args) {
     int[] zahl1 = {1,2,3};
     int[] zahl2 = {7,8,9};

    //Add arrays zahl1 and zahl2.
    int [] zwischenarray = add(zahl1, zahl2);
    for (int i = 0; i < zwischenarray.length; i++) {
        System.out.println(zwischenarray[i]);
    }
}


private static int[] add(int[] zahl1, int[] zahl2) {
    int len;
    if (zahl1.length < zahl2.length) {
        len = zahl2.length;
    } else {
        len = zahl1.length;
    }

    int[] finalresult = new int [len + 1];
    int carryover = 0;

    for (int i = 0; i <= len-1; i++) {
        int a = (zahl1[i]);
        int b = (zahl2[i]);
        int c = a + b + carryover;
        if (c > 9) {
            carryover = 1;
            c = c - 10;
        } else {
            carryover = 0;
        }
        finalresult[i] = c;
    }

    if (carryover == 1) {
        finalresult[len] = 1;
    }

    return finalresult;
}

}

Solution 2:[2]

Your code is conflicted: The numbers / characters in your array are actually integers, not "printable" or "human readable" characters. But, parts of your code are treating them as if they are "printable".

Let's go back decades, and use ASCII for the beginning of this explanation. ASCII has "Printable" and "Nonprintable" characters. The "Nonprintable" characters are known as "Control codes."

Control codes include codes that move the cursor on a display terminal or print head on a printing terminal. They include thing like CR (Carriage Return), LF (Line Feed), HT (Horizontal tab), and BS (Backspace). Others are used by data communications hardware to control the flow of data, or to report status.

Printable characters correspond to what you see on a terminal screen or printout. They include uppercase alphabetic, lower case alphabetic, digits, punctuation, and the space character. They are "human readable."

Look at the list of printable characters in the Wikipedia article. Take 5 as an example. It's represented as '53' in base ten, which corresponds to '35' in base sixteen, or '011 0101' in binary. Note that it is not the same as the binary number five, which would be '0000 0101'.

Java uses 16 bit Unicode, not ASCII, for its char type. The Java compiler allows arithmetic to be done on char data, as if it was the same as short.

These lines in your code expect your char variables and constants are printable characters:

int a = Character.getNumericValue(zahl1[i]);            
int b = Character.getNumericValue(zahl2[i]);

In addition, that you specified zwischenarray as char tells the compiler to handle the contents as printable characters in this line:

System.out.println(zwischenarray[i]);

But, the rest of your code treats your char data as integer data types.

You have a bug in this line: finalresult[len + 1] = 1;. After that bug is fixed, how do you fix the rest of your code? There are different ways, and which is best depends on your intention.

For demonstration purpose, try this: Replace the following

int a = Character.getNumericValue(zahl1[i]);            
int b = Character.getNumericValue(zahl2[i]);
int c = a + b + carryover;

with

int c = zahl1[i] + zahl2 [i] + carryover; 

Also, put a cast in your output line:

System.out.println((short)zwischenarray[i]);

And run it. That will demonstrate you can do arithmetic on Java char data.

Now, remove the (short) cast in output line, and change all occurrences of char to short (or int). Your program still works.

This is because of the way you entered the values for zahl1 and zahl2. Your source code consists of printable characters and white space. By omitting the single quotes, you told the compiler to convert the values to binary integers. For example, your source code 9 became binary 0000 1001 in the runtime code. If you wanted your 9 to remain as a printable character, you needed to enclose it in single quote marks: '9' .

By enclosing all the values in zahl1 and zahl2 in single quote marks, the use of Character.getNumericValue is appropriate. But, you would still need the (short) or (int) cast in your System.out. line to see your output.

Character.getNumericValue is returning -1 because the values passed are outside of the range it was designed to work with.

Here are two ways to convert a base 10 digit represented as a binary integer to the equivalent printable character:

 finalresult[i] = (char)  (c + '0');

But, my preference is for this:

 final String digit = "0123456789";
 finalresult[i] = digit.charAt (c);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 katyRosale
Solution 2