gpt4 book ai didi

java - 如何从 Java 中的 for 循环返回多个字符串?

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

我正在使用 for 循环,每次循环都需要返回一个字符串,但使用“return”会中断循环,Eclipse 会抛出“Unreachable Code”错误。有什么建议

最佳答案

我觉得你的逻辑有问题

for (int counter = 0; counter < possibleAnswers.length; counter++){
// This condition will be meet immediately because 0 is less then 25...
if (counter < 25){
return alpha[counter] + ": " + possibleAnswers[counter] + "\n";
}
// Meaning it is impossible for the program to ever reach this line...
if (counter >= 26){
return alpha[26] + a + ": " + possibleAnswers[counter] + "\n";
a++;
}
}

我认为你最好尝试类似...

StringBuilder sb = new StringBuilder(25);
for (int counter = 0; counter < possibleAnswers.length; counter++){
if (counter < 25){
sb.append(alpha[counter] + ": " + possibleAnswers[counter] + "\n");
}
if (counter >= 26){
sb.append(alpha[26] + a + ": " + possibleAnswers[counter] + "\n");
a++;
}
}
return sb.toString();

更新工作示例

String possibleAnswers[] = new String[30];
String alpha[] = new String[30];

for (int index = 0; index < 30; index++) {
possibleAnswers[index] = "Happy " + index;
alpha[index] = Integer.toString(index);
}

int a = 0;

StringBuilder sb = new StringBuilder(25);
for (int counter = 0; counter < possibleAnswers.length; counter++) {
if (counter < 25) {
sb.append(alpha[counter]).append(": ").append(possibleAnswers[counter]).append("\n");
}
if (counter >= 26) {
sb.append(alpha[26]).append(a).append(": ").append(possibleAnswers[counter]).append("\n");
a++;
}
}

System.out.println(sb);

哪些输出

0: Happy 0
1: Happy 1
2: Happy 2
3: Happy 3
4: Happy 4
5: Happy 5
6: Happy 6
7: Happy 7
8: Happy 8
9: Happy 9
10: Happy 10
11: Happy 11
12: Happy 12
13: Happy 13
14: Happy 14
15: Happy 15
16: Happy 16
17: Happy 17
18: Happy 18
19: Happy 19
20: Happy 20
21: Happy 21
22: Happy 22
23: Happy 23
24: Happy 24
260: Happy 26
261: Happy 27
262: Happy 28
263: Happy 29

关于java - 如何从 Java 中的 for 循环返回多个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12633249/

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