我有一个java程序,其中我想要实现以下目标:
first input: ABC
second input: xyz
output: AxByCz
我的Java程序如下:
import java.io.*;
class DisplayStringAlternately
{
public static void main(String[] arguments)
{
String firstC[], secondC[];
firstC = new String[] {"A","B","C"};
secondC = new String[] {"x","y","z"};
displayStringAlternately(firstC, secondC);
}
public static void displayStringAlternately (String[] firstString, String[] secondString)
{
int combinedLengthOfStrings = firstString.length + secondString.length;
for(int counter = 1, i = 0; i < combinedLengthOfStrings; counter++, i++)
{
if(counter % 2 == 0)
{
System.out.print(secondString[i]);
}
else
{
System.out.print(firstString[i]);
}
}
}
}
但是我遇到以下运行时错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
AyC at DisplayStringAlternately.displayStringAlternately(DisplayStringAlternately.java:23)
at DisplayStringAlternately.main(DisplayStringAlternately.java:12)
Java Result: 1
我的 Java 程序出了什么错误?
如果两个数组的长度相同for
循环应该继续 whilei < anyArray.length
.
而且你不需要任何counter
以确定您应该首先打印哪个数组。只需硬编码将打印的第一个元素firstString
下一张来自secondString
.
So your displayStringAlternately
方法可以看起来像
public static void displayStringAlternately(String[] firstString,
String[] secondString) {
for (int i = 0; i < firstString.length; i++) {
System.out.print(firstString[i]);
System.out.print(secondString[i]);
}
}
无论如何你的代码会抛出ArrayIndexOutOfBoundsException
因为每次您决定从哪个数组打印元素递增i
,所以你可以通过这种方式有效地跳过数组
i=0 i=2
{"A","B","C"};
{"x","y","z"};
i=1 i=3
^^^-here is the problem
因此,正如您所看到的,您的代码尝试访问第二个数组中不在其中的元素(它超出了其范围)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)