0

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);
        
        
    }
}
5
  • 3
    "full of mistakes and all i could get is an empty output" You should tell us the specifics about at least 1 of those errors and also which line of code were you expecting to print some output? Commented Nov 17, 2020 at 16:49
  • 2
    Do you know how to use the debugger? Commented Nov 17, 2020 at 16:51
  • 1
    Please limit your post to only one of your function examples and include the errors you get with it Commented Nov 17, 2020 at 16:59
  • By the way, to work with very large integer numbers, use the BigInteger class built into Java. Commented Nov 17, 2020 at 17:16
  • This is not difficult but more so than you may realize. For example, you need to handle carry over from one addition to the next. So since 6 + 6 is 12 you need to put 2 in the array location and carry 1 over to the next addition. This also means that if index 0 adds to where a carry is generated, you need to decide how to handle it since you can't carry to location of -1. So you either copy the array or declare overflow. Commented Nov 17, 2020 at 17:23

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much for the detailed explanation. It made every concept that I was looking very clear.
You are welcome. And do not forget to up vote if you find this helpful. Happy Coding

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.