gpt4 book ai didi

java - java 循环输出中不需要的重复

转载 作者:行者123 更新时间:2023-12-02 15:13:32 25 4
gpt4 key购买 nike

我正在编写代码来 reshape 信号。我得到的输出带有不需要的重复。

输入:

String[] rani = {"A","1","2","OK","B","3","4","OK","B","1","3","OK"};

所需输出:

A/3 B/7 B/4

得到输出:

A/3 A/3 A/3 A/3 B/7 B/7 B/7 B/7 B/4


算法:单个字母字符串(“A”、“B”等)后跟数字字符串(“1”、“2”等)。每个字母字符串后跟斜杠和数字总数,字符串“OK”将被忽略。

作为 java 和编程的新手,我需要帮助才能获得所需的输出。

我的代码是:

public class SignalOK {

public static void main(String[] arg) {
String finalSignal = "";
String netSignal = "";
String name = "";
int total = 0;
String[] rani = { "A", "1", "2", "OK", "B", "3", "4", "OK", "B", "1",
"3", "OK" };

for (int i = 0; i < rani.length; i++) {

if ((rani[i] == "A") || (rani[i] == "B")) {

name = rani[i];
}

if ((rani[i] == "1") || (rani[i] == "2") || (rani[i] == "3")
|| (rani[i] == "4")) {

total = total + Integer.valueOf(rani[i]);
}

if (rani[i] == "OK") {

netSignal = name + "/" + String.valueOf(total) + " ";
name = "";
total = 0;
}
finalSignal = finalSignal + netSignal;
}

System.out.println(finalSignal);
}
}

最佳答案

只需将最终结果字符串连接移动到 "OK" if 括号内:

if (rani[i].equals("OK")) {
netSignal = name + "/" + String.valueOf(total) + " ";
name = "";
total = 0;
finalSignal = finalSignal + netSignal;
}

此外,始终使用 .equals() 来比较字符串。

关于java - java 循环输出中不需要的重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31206842/

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