I'm trying to write a code that take a string : (7+5)*(6+9)
and return the string : 7*6 + 7*9 + 5*6 + 5*9
my algorithm is to create 2 char arrays (for this example : 75,69)
and run in O^2 loop in this 2 arrays and copy value from first array , * value from second array, +. i get index of bounds exception and don't understand why.
this is my code :
String s = "((7+5)*(6+9))";
char[] ch = s.toCharArray();
char[] newCh = new char[30];
int j=0;
int blocks = 2;
int newi = 0;
for (int i=0 ; i<ch.length ; i++) {
if (ch[i]=='(' && ch[i+1]!='(') {
j=i+1;
while (blocks>0) {
if (ch[j]==')') {
blocks--;
newCh[newi]='-';
newi++;
}
if (ch[j]!='+' && ch[j]!='*' && ch[j]!=')' && ch[j]!='(') {
if (blocks==0) {
break;
}
else {
newCh[newi]=ch[j];
newi++;
}
}
j++;
}
}
continue;
}
System.out.println("new Char array : ");
for (int i=0 ; i<newCh.length ; i++) {
System.out.print(newCh[i]);
}
System.out.println();
Multy(newCh);
and my multy method :
public static char[] Multy(char[] ch) {
char[] newc = new char[50];
char[] c1 = new char[30];
char[] c2 = new char[30];
int newi = 0;
int i1 = 0;
int i2 = 0;
int flag = 0;
for (int i=0 ; i<ch.length ; i++) {
if (ch[i]!='-') {
if (flag ==0) {
c1[i1] = ch[i];
i1++;
}
else {
if (ch[i]!='-')
c2[i2]= ch[i];
i2++;
}
}
if (ch[i]=='-')
flag = 1;
}
System.out.println("In func");
System.out.print("c1 : ");
for (int i=0 ; i<c1.length ; i++) {
System.out.print(c1[i]);
}
System.out.println();
System.out.print("c2 : ");
for (int i=0 ; i<c1.length ; i++) {
System.out.print(c2[i]);
}
///////////
for (int i=0 ; i<c1.length ; i++) {
for (int j=0 ; j<c2.length ; j++) {
newc[newi]=c1[i];
newc[newi+1] = '*';
newc[newi+2] = c2[j];
newc[newi+3] = '+';
newi+=4;
}
}
System.out.print("NEWc2 : ");
for (int i=0 ; i<newc.length ; i++) {
System.out.print(newc[i]);
}
return newc;
}