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;
}
}