我正在尝试编写一个接受字符串的代码:(7+5)*(6+9)
并返回字符串:7*6 + 7*9 + 5*6 + 5*9
我的算法是创建 2 个字符数组(例如:75,69)并在这 2 个数组中的 O^2 循环中运行并从中复制值第一个数组,* 来自第二个数组的值,+。我得到边界异常的索引,但不明白为什么。
这是我的代码:
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);
和我的多种方法:
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;
}
在 te double for 循环中,您迭代到数组的末尾(c1.length 和 c2.length),同时在循环 newc[newi+X] 中添加一个数字,但是因为您循环到最后,您将用完位置你会得到 IndexOutOfBoundsException ......
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;
}
}
更新:
额外的解释:-)
如果你做这样的事情:
public class ArrayExample {
public static void main(String[] args) {
String[] strings = new String[3];
System.out.println("strings.length = " + strings.length);
strings[4] = "foo";
}
}
输出将是:
strings.length = 3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at nl.ivonet.ArrayExample.main(ArrayExample.java:26)
这是因为我试图在字符串数组的索引 4 处分配一个值,但字符串数组被初始化new String[3]
为固定大小为 3。这就是出错的原因以及您的代码失败的原因。数组与列表不同。数组是固定大小的,而列表不是。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句