gpt4 book ai didi

Java代码打印正确但返回错误

转载 作者:太空宇宙 更新时间:2023-11-04 14:48:09 25 4
gpt4 key购买 nike

以下代码:

public class NewClass1 {

public static String mus = "";

public static String musCal(String[] signal, int[] time) {
int i = 0;
while (i < signal.length) {
switch (signal[i]) {
case "x": {
// System.out.print("x = ");
mus = mus + "x";
int sum = time[i];
if (signal[i + 1] == "C") {
i++;
while (i < signal.length && signal[i] == "C") {
sum += time[i];
i++;
}
} else
i++;
// System.out.print(sum + " ");
mus = sum + " ";
break;
}
case "y": {
// System.out.print("y = ");
mus = mus + "y ";
int sum = time[i];
if (signal[i + 1] == "C") {
i++;
while (i < signal.length && signal[i] == "C") {
sum += time[i];
i++;
}
} else
i++;
// System.out.print(sum + " ");
mus = sum + " ";

break;
}
case "z": {

// System.out.print("z = ");
mus = mus + "z ";
int sum = time[i];
if (signal[i + 1] == "C") {
i++;
while (i < signal.length && signal[i] == "C") {
sum += time[i];
i++;
}
} else
i++;
// System.out.print(sum + " ");
mus = sum + " ";

break;
}
}
}
return mus;
}

public static void main(String[] args) {
String signal[] = { "x", "y", "y", "C", "C", "z", "C", "C", "x", "C" };
int time[] = { 2, 5, 1, 4, 7, 8, 2, 6, 4, 3 };

musCal(signal, time);
System.out.print(mus);
}
}

代码的预期输出是:

x=2  y=5  y=12  z=16  x=7

如果注释符号//被删除以激活 System.out.print 语句,则代码会给出预期的输出。但是,当我尝试以“String mus”的形式收集此输出时,如代码所示,我只得到了输出字符串的最后一个元素,即 7。作为 java 和编程的新手,我需要你的帮助。请帮助我更正 return 语句,以便我可以通过连接或任何其他合适的方法获得正确的输出,如 String 'mus'。

最佳答案

您还可以将此解决方案用于:

替换mus=sum + "";mus += sum + "";

关于Java代码打印正确但返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24138029/

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