0

I am trying to find the sum using strings but getting error :

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
    at java.lang.String.charAt(String.java:658)
    at Main.sum(Main.java:48)
    at Main.main(Main.java:28)

Here is my Code:

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        sc.nextLine();
        while(t > 0) {
            int n = sc.nextInt();
            sc.nextLine();
            String str[] = new String[n+2];
            System.out.println("TEST : ");
            for(int i = 0;i < n;i++) {
                str[i] = sc.next();
            }
            //sc.nextLine();
            for(String i : str) {
                System.out.print(i + " ");
            }
            for(int j = 1;j < n;j++) {
                str[j] = sum(str[j-1],str[j]);
            }
            System.out.println(str[n-1]);
            t--;
        }
    }

    public static String sum(String s2, String s1) {
        int n1 = s1.length();
        int n2 = s2.length();
        String res = "";
        if(n2 >= n1) {
            int carry = 0;
            int sum = 0;
            for(int i = n2 - 1, j = n1 - 1;i >= n1 - 1  && j >= 0;i--, j--) {
                sum = ((int)(s1.charAt(j) - '0') + (int)(s2.charAt(i) - '0') + carry);
                carry = sum / 10;
                res += (char)(sum % 10 + '0');
            }
            for(int i = n1;i >= 0;i--) {
                sum = ((int)(s2.charAt(i) - '0') + carry);
                carry = sum / 10;
                res += (char)(sum % 10 + '0');
            }

        } else {
            sum(s2,s1);
        }
        //String s3 = res.reverse().toString();
        return res;
    }
}
VGR
  • 40,506
  • 4
  • 48
  • 63
  • 1
    change this ` for(int i = n1;i >= 0;i--)` to ` for(int i = n1-1;i >= 0;i--)`. – vb_rises Jan 02 '20 at 18:09
  • Please see https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors. – VGR Jan 02 '20 at 18:14
  • If you need to work with integers up to 100 digits in length, then use [`BigInteger`](https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html). – Andreas Jan 02 '20 at 19:25
  • Actually the problem was to use strings to solve the problem and I realized that the max value of i should be n2 - n1 and the reverse string is to be returned. – SAIKAT DAS Jan 04 '20 at 13:04

0 Answers0