learningJava2020
learningJava2020

Reputation: 117

String Number Addition Java

This is my second week learning Java and I'm trying to implement some functions that I saw in the book I'm studying with.

With the first function I wanted to represent an integer as an array of integer digits so that I can bypass the range of integer values.

For example:


1st Function

Input : integerInput(123456)

Output : integerString[] = {1,2,3,4,5,6}

2nd function

Input : stringInput[] = {123456}

Output : integerString[] = {1,2,3,4,5,6}

3rd function:

(I want to add the 2 integer string values as in like normal addition)

Input : integerString1[] = {1,2,3,4,5,6} integerString2[] = {1,2,3,4,5,6}

Output : [2,4,6,9,1,2]


This is what I have so far, it is full of mistakes and all i could get is an empty output. Would appreciate any help.

Thanks.

public class tryingOut{
    
    public static int[] integerToNumberArray(int value) {
        String temp = Integer.toString(value);
        int[] list = new int[temp.length()];
        for (int i = 0; i < temp.length(); i++) {
            list[i] = temp.charAt(i) - '0';
        }
        return list;
    }
    
    public static boolean isNumeric(String value) {
        if (value == null) {
            return false;
        }
        try {
            int d = Integer.parseInt(value);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }
    
    public static int[] stringToNumberArray(String value) {
        
        boolean checkNumeric = isNumeric(value);
        
        if (checkNumeric = false) {
            return null;
        } else {
            String[] items = value.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\s", "").split(",");
            
            int[] results = new int[items.length];
            
            for (int i = 0; i < items.length; i++) {
                try {
                    results[i] = Integer.parseInt(items[i]);
                } catch (NumberFormatException nfe) {
                    
                }
            }
            return results;
        }
    }
    
    public static int[] addNumberArrays(int[] a1, int[] a2) {
        int[] result = null;
        
        return result;
    }
    
    public static void main(String[] args) {
        
        int test1 = 19;
        int test2 = 823;
        int[] list1 = integerToNumberArray(test1);
        int[] list2 = integerToNumberArray(test2);
        
        //  stringToNumberArray(test1);
        //  stringToNumberArray(test2);
        
        
    }
}

Upvotes: 0

Views: 303

Answers (1)

Welcome to the world of Programming with JAVA. Firstly, I appreciate your enthusiasm for programming and the efforts you made.

As mentioned in the comments by Basil Bourque you can achieve this by BigInteger. However, I like your interest for trying this yourself and therefore I will try to share a code below with as much description I can provide to make it understable to you.


To point out few mistakes in your original code:

  1. You do not need to handle null separtely with if-condition for your method isNumeric(String value) becaause the try-catch block will automatically handle it for you.

  2. For stringToNumberArray(String value) method you do not need to use the String.split and also it was quite unclear what you did there in line String[] items = ...


Full code:

public class PlayingWithInt {
    
    public static boolean isNumeric(String value) {
        try {
            Integer.parseInt(value);
        } catch (NumberFormatException nfe) {
            // This handles both null and other non int values so we don't need an extra condition to check for null
            return false;
        }
        return true;
    }
    
    // Assuming argument value is "123456"
    public static int[] stringToNumberArray(String value) {
        if (isNumeric(value)) { // We generally don't write `== true` or `== false` with boolean values
            char[] valueAsCharArray = value.toCharArray(); // valueAsCharArray = {'1', '2', '3', '4', '5', '6'}
            int[] valueAsIntArray = new int[valueAsCharArray.length]; // valueAsIntArray = {0, 0, 0, 0, 0, 0}
            
            for (int i = 0; i < valueAsCharArray.length; i++) {
                valueAsIntArray[i] = valueAsCharArray[i] - '0';
            }
            return valueAsIntArray; // valueAsCharArray = {1, 2, 3, 4, 5, 6}
        }
        return null; // Null will be returned if the value is not numeric
    }
    
    // Assuming argument value is {"1", "2", "3", "4", "5", "6"}
    public static int[] stringToNumberArray(String[] value) {
        int[] valueAsIntArray = new int[value.length]; // valueAsIntArray = {0, 0, 0, 0, 0, 0}
        
        for (int i = 0; i < value.length; i++) {
            valueAsIntArray[i] = value[i].charAt(0) - '0';
        }
        return valueAsIntArray; // valueAsCharArray = {1, 2, 3, 4, 5, 6}
    }
    
    // Let's say value is 123456
    public static int[] integerToNumberArray(int value) {
        String valueAsString = Integer.toString(value); // valueAsString = "123456"
        return stringToNumberArray(valueAsString); // We are using our already built method that does the same thing.
    }
    
    public static int[] addNumberArrays(int[] a1, int[] a2) {
        int maxLength;
        if (a1.length > a2.length) maxLength = a1.length;
        else maxLength = a2.length;
        
        int[] result = new int[maxLength + 1];
        
        int i = a1.length - 1; // Index iterator for a1
        int j = a2.length - 1; // Index iterator for a2
        int k = result.length - 1; // Index iterator for result
        int carry = 0; // carry to handle case when the sum of two digits more than deci/ ten (10)
        
        while (i >= 0 && j >= 0) {
            int sum = a1[i] + a2[j] + carry;
            result[k] = sum % 10;
            carry = sum / 10;
            i--;
            j--;
            k--;
        }
        
        // If a1 has more digits than a2
        while (i >= 0) {
            int sum = a1[i] + carry;
            result[k] = sum % 10;
            carry = sum / 10;
            i--;
            k--;
        }
        
        // If a2 has more digits than a1
        while (j >= 0) {
            int sum = a2[j] + carry;
            result[k] = sum % 10;
            carry = sum / 10;
            j--;
            k--;
        }

        result[0] = carry;
    
        return result;
    }
    
    public static void main(String[] args) {
        int test1 = 123456;
        int test2 = 123456;
        int[] num1 = integerToNumberArray(test1);
        int[] num2 = integerToNumberArray(test2);
        int[] result = addNumberArrays(num1, num2);
        
        for (int i : result) System.out.print(i); // This is known as enhanced-for-loop or for-each-loop
        
        System.out.println();        
    }
}

Output:

0246912

Additional Input and Output:

Example 1

Code:

public static void main(String[] args) {
    int test1 = 19;
    int test2 = 823;
    int[] num1 = integerToNumberArray(test1);
    int[] num2 = integerToNumberArray(test2);
    int[] result = addNumberArrays(num1, num2);
    
    for (int i : result) System.out.print(i); // This is known as enhanced-for-loop or for-each-loop
    
    System.out.println();        
}

Output:

0842

Example 2

Code:

public static void main(String[] args) {
    int test1 = 823;
    int test2 = 19;
    int[] num1 = integerToNumberArray(test1);
    int[] num2 = integerToNumberArray(test2);
    int[] result = addNumberArrays(num1, num2);
    
    for (int i : result) System.out.print(i); // This is known as enhanced-for-loop or for-each-loop
    
    System.out.println();        
}

Output:

0842

Example 3

Code:

public static void main(String[] args) {
    int test1 = 999;
    int test2 = 999;
    int[] num1 = integerToNumberArray(test1);
    int[] num2 = integerToNumberArray(test2);
    int[] result = addNumberArrays(num1, num2);
    
    for (int i : result) System.out.print(i); // This is known as enhanced-for-loop or for-each-loop
    
    System.out.println();        
}

Output:

1998

References:

  1. String.toCharArray()

  2. Enhanced for-loop |OR| For-Each Loop

  3. Integer.parseInt(String value)

Upvotes: 1

Related Questions