gpt4 book ai didi

java - 在括号内查找数字

转载 作者:行者123 更新时间:2023-12-04 05:54:23 29 4
gpt4 key购买 nike

作为我项目的一部分,我需要能够在这些括号内添加数字,我已经研究了太久但没有结果,我将不胜感激任何帮助

String[] s = "1 2 3 ( 4 5 6 ) * 1000 7 8".split("\\s");

例如在这种情况下有 3 个数字

这是我到目前为止:
while(st.hasMoreTokens()) {
if ( st.nextToken() != "(" )
count = count +1 ;
}
if ( st.nextToken() == "(" )
while (st.nextToken() != ")") {
count2 = count2 + 1;
}
System.out.println(count); System.out.println(count2);
}

最佳答案

没有完全理解这里的用例。假设你总是只有一组括号 [ "("和 ")"],永远不会有括号不匹配,你不关心括号外的其他数字/数字/运算符,简单的方法在括号之间添加数字将是

String mainStr = "1 2 3 ( 4 5 6 ) * 1000 7 8";
String []inside = mainStr.substring(mainStr.indexOf("(")+1, mainStr.indexOf(")")
.split("\s");
int sum = 0;
int innerNum = 0;
for (int i=0; i<inside.length;i++) {
try {
innerNum = Integer.parseInt(inside[i]);
} catch (NumberFormatException e) {
innerNum = 0;
}
sum = sum + innerNum;
}
return sum;

对于多组括号(不是嵌套的),我们可以遍历 mainStr 以获取下一组,并以相同的方式进行

关于java - 在括号内查找数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9694814/

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