gpt4 book ai didi

java - Java中2个字符串的交替显示

转载 作者:行者123 更新时间:2023-11-30 07:07:11 25 4
gpt4 key购买 nike

我有一个 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循环应该在 i < anyArray.length 时继续.

你也不需要任何 counter以确定您应该首先打印哪个数组。只需硬编码第一个元素将从 firstString 打印出来下一个来自 secondString .

所以你的 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

因此,正如您所见,您的代码尝试访问不在其中的第二个数组中的元素(超出范围)。

关于java - Java中2个字符串的交替显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25084200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com