{"id":9799,"date":"2022-09-20T19:36:13","date_gmt":"2022-09-20T14:06:13","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/"},"modified":"2022-09-20T19:36:13","modified_gmt":"2022-09-20T14:06:13","slug":"solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/","title":{"rendered":"[Solved] ArrayIndexOutOfBoundsException in ten&#8217;s complement arithmetic implementation"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-27213764\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"27213764\" data-parentid=\"27181778\" data-score=\"1\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<p>Okay, after so much discussion and so many issues with your code I have totally revised your original code because you said you wanted to learn more. Among other improvements I have done the following changes:<\/p>\n<ul>\n<li>Meaninfgul class name<\/li>\n<li>Meaningful method and parameter names<\/li>\n<li>Convert repeated and often used constants like <code>50<\/code> and the array representation of the number <code>1<\/code> (needed for negation) into static final members for clean code reasons (documentation, easy change in one place, meaningful names), runtime optimisation).<\/li>\n<li>Extend the code to permit negative integers as operands<\/li>\n<li>Added validation patterns for user input. E.g. now the maximum number length is checked in order to avoid an array overflow.<\/li>\n<li>Avoid numeric overflows during calculation by making the array bigger than the maximum number of digits permitted for user input (see source code comments)<\/li>\n<li>Add retry loops with error handling for operand and operator input, extract console handling into one parametrised method.<\/li>\n<li>Simplify code by removing unnecessary checks because user input is already validated before converting it into an <code>int[]<\/code>.<\/li>\n<li>Make debug output optional<\/li>\n<\/ul>\n<pre class=\"lang-java prettyprint-override\"><code>package de.scrum_master.stackoverflow;\n\nimport java.util.Arrays;\nimport java.util.Scanner;\nimport java.util.regex.Pattern;\n\npublic class TensComplementArithmetic {\n    \/\/ Print debug messages?\n    private static final boolean DEBUG = true;\n\n    \/\/ Maximum length for numbers entered by a user\n    \/\/ (number of digits excluding the optional +\/- sign)\n    private static final int MAX_NUMBER_LENGTH = 50;\n\n    \/\/ Array must have one additional element for the sign and\n    \/\/ one more to avoid overflows when adding big negative numbers\n    private static final int ARRAY_LENGTH = MAX_NUMBER_LENGTH + 2;\n\n    \/\/ Scanner for console input handling\n    private static final Scanner INPUT_SCANNER = new Scanner(System.in);\n\n    \/\/ Regex pattern for positive\/negative integer number format verification incl. length check\n    private static final Pattern INTEGER_PATTERN = Pattern.compile(\"[+-]?[0-9]{1,\" + MAX_NUMBER_LENGTH + \"}\");\n\n    \/\/ Regex pattern for operator verification (currently only \"+\"https:\/\/stackoverflow.com\/\"-\" allowed)\n    private static final Pattern OPERATOR_PATTERN = Pattern.compile(\"[+-]\");\n\n    \/\/ The number 1 is always needed for converting a 9's into a 10's complement\n    \/\/ during negation, so we define it as a reusable constant\n    private static final int[] NUMBER_ONE;\n\n    static {\n        \/\/ Initialise constant carrying array representation for number 1\n        NUMBER_ONE = new int[ARRAY_LENGTH];\n        NUMBER_ONE[ARRAY_LENGTH - 1] = 1;\n    }\n\n    public static String readConsoleInput(String prompt, Pattern validationPattern, String errorMessage) {\n        String input = null;\n        while (input == null) {\n            System.out.print(prompt + \": \");\n            if (INPUT_SCANNER.hasNext(validationPattern))\n                input = INPUT_SCANNER.next(validationPattern);\n            else {\n                INPUT_SCANNER.nextLine();\n                System.out.println(errorMessage);\n            }\n        }\n        return input;\n    }\n\n    public static String getOperand(String operandName) {\n        return readConsoleInput(\n            \"Operand \" + operandName,\n            INTEGER_PATTERN,\n            \"Illegal number format, please enter a positive\/negative integer of max. \" + MAX_NUMBER_LENGTH + \" digits.\"\n        );\n    }\n\n    private static String getOperator() {\n        return readConsoleInput(\n            \"Arithmetical operator (+ or -)\",\n            OPERATOR_PATTERN,\n            \"Unknown operator, try again.\"\n        );\n    }\n\n    public static int[] parseInteger(String number) {\n        char sign = number.charAt(0);\n        boolean isNegative = sign == '-' ? true : false;\n        if (isNegative || sign == '+')\n            number = number.substring(1);\n\n        int[] result = new int[ARRAY_LENGTH];\n        int parsePosition = number.length() - 1;\n        for (int i = result.length - 1; i &gt;= 0; i--) {\n            if (parsePosition &lt; 0)\n                break;\n            result[i] = number.charAt(parsePosition--) - '0';\n        }\n        return isNegative ? negate(result) : result;\n    }\n\n    public static int[] add(int[] operand1, int[] operand2) {\n        int[] result = new int[ARRAY_LENGTH];\n        int carry = 0;\n\n        for (int i = ARRAY_LENGTH - 1; i &gt;= 0; i--) {\n            result[i] = operand1[i] + operand2[i] + carry;\n            if (result[i] &gt;= 10) {\n                result[i] = result[i] % 10;\n                carry = 1;\n            } else\n                carry = 0;\n        }\n        return result;\n    }\n\n    public static int[] complement(int[] operand) {\n        int[] result = new int[ARRAY_LENGTH];\n\n        for (int i = operand.length - 1; i &gt;= 0; i--)\n            result[i] = 9 - operand[i];\n        return result;\n    }\n\n    public static int[] negate(int[] operand) {\n        return add(complement(operand), NUMBER_ONE);\n    }\n\n    public static void print(int[] result, String operation) {\n        System.out.print(operation.charAt(0) == '-' ? \"Difference = \" : \"Sum = \");\n        if (result[0] == 9) {\n            result = negate(result);\n            System.out.print(\"-\");\n        }\n        boolean leadingZero = true;\n        for (int i = 0; i &lt; result.length; i++) {\n            if (leadingZero) {\n                if (result[i] == 0)\n                    continue;\n                leadingZero = false;\n            }\n            System.out.print(result[i]);\n        }\n        System.out.println(leadingZero ? \"0\" : \"\");\n    }\n\n    public static void main(String[] args) {\n        int[] operand1 = parseInteger(getOperand(\"#1\"));\n        int[] operand2 = parseInteger(getOperand(\"#2\"));\n        String operator = getOperator();\n\n        if (operator.equals(\"-\"))\n            operand2 = negate(operand2);\n\n        int[] result = new int[ARRAY_LENGTH];\n        result = add(operand1, operand2);\n        if (DEBUG) {\n            System.out.println(\"Operand #1 = \" + Arrays.toString(operand1));\n            System.out.println(\"Operand #2 = \" + Arrays.toString(operand2));\n            System.out.println(\"Result     = \" + Arrays.toString(result));\n        }\n        print(result, operator);\n    }\n}\n<\/code><\/pre>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\"><\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved ArrayIndexOutOfBoundsException in ten&#8217;s complement arithmetic implementation <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] Okay, after so much discussion and so many issues with your code I have totally revised your original code because you said you wanted to learn more. Among other improvements I have done the following changes: Meaninfgul class name Meaningful method and parameter names Convert repeated and often used constants like 50 and the &#8230; <a title=\"[Solved] ArrayIndexOutOfBoundsException in ten&#8217;s complement arithmetic implementation\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/\" aria-label=\"More on [Solved] ArrayIndexOutOfBoundsException in ten&#8217;s complement arithmetic implementation\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[361,652,323],"class_list":["post-9799","post","type-post","status-publish","format-standard","hentry","category-solved","tag-arrays","tag-int","tag-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>[Solved] ArrayIndexOutOfBoundsException in ten&#039;s complement arithmetic implementation - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] ArrayIndexOutOfBoundsException in ten&#039;s complement arithmetic implementation - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] Okay, after so much discussion and so many issues with your code I have totally revised your original code because you said you wanted to learn more. Among other improvements I have done the following changes: Meaninfgul class name Meaningful method and parameter names Convert repeated and often used constants like 50 and the ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-09-20T14:06:13+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] ArrayIndexOutOfBoundsException in ten&#8217;s complement arithmetic implementation\",\"datePublished\":\"2022-09-20T14:06:13+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/\"},\"wordCount\":191,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\"arrays\",\"int\",\"java\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/\",\"name\":\"[Solved] ArrayIndexOutOfBoundsException in ten's complement arithmetic implementation - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2022-09-20T14:06:13+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] ArrayIndexOutOfBoundsException in ten&#8217;s complement arithmetic implementation\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] ArrayIndexOutOfBoundsException in ten's complement arithmetic implementation - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] ArrayIndexOutOfBoundsException in ten's complement arithmetic implementation - JassWeb","og_description":"[ad_1] Okay, after so much discussion and so many issues with your code I have totally revised your original code because you said you wanted to learn more. Among other improvements I have done the following changes: Meaninfgul class name Meaningful method and parameter names Convert repeated and often used constants like 50 and the ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/","og_site_name":"JassWeb","article_published_time":"2022-09-20T14:06:13+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] ArrayIndexOutOfBoundsException in ten&#8217;s complement arithmetic implementation","datePublished":"2022-09-20T14:06:13+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/"},"wordCount":191,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["arrays","int","java"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/","url":"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/","name":"[Solved] ArrayIndexOutOfBoundsException in ten's complement arithmetic implementation - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-09-20T14:06:13+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-arrayindexoutofboundsexception-in-tens-complement-arithmetic-implementation\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] ArrayIndexOutOfBoundsException in ten&#8217;s complement arithmetic implementation"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/9799","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=9799"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/9799\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=9799"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=9799"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=9799"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}