gpt4 book ai didi

java - 减去字符串

转载 作者:行者123 更新时间:2023-12-01 23:23:33 25 4
gpt4 key购买 nike

我被要求创建一个 JOptionPane该程序接受用户想要的任意数量的数字(作为字符串)并将它们相加。我想到了这样的伪:

  1. 制作int Total = 0
  2. 接收字符串 X 形式的输入
  3. 循环:for (int i = 0; i<=X.length();i++)
    1. 创建另一个字符串 S1它获取从开头到第一个空格的数字
    2. 转换S1转化为一个数字并将其添加到总计
    3. 减去S1来自X ,然后开始循环
  4. 显示总计

所以,我的问题是减去 S1来自X

到目前为止我的代码:

public static void main(String[] args) {
int total = 0;
String x = JOptionPane.showInputDialog("enter nums please");
for (int i = 0; i<=x.length();i++){
String s1 = x.substring (0, x.indexOf(' '));
total += Integer.parseInt(s1);
x = x - s1;
}
JOptionPane.showMessageDialog(null, "the sum is" + total); }

最佳答案

如果你还没有学习数组,你可以这样实现:

public static void main(String[] args){
int total = 0;
String x = "12 7";
String s1 = x.trim(); //trim the string
while(!s1.isEmpty()){ //loop until s1 is not empty
int index = x.indexOf(' ');//search the index for a whitespace
if(index != -1){ //we found a whitespace in the String !
s1 = s1.substring(0, index); //substract the right number
total += Integer.parseInt(s1);
x = x.substring(index+1).trim(); //update the String x by erasing the number we just added to total
s1 = x; //update s1
} else {
total += Integer.parseInt(s1); //when there is only one integer left in the String
break; //break the loop this is over
}
}
System.out.println(total);
}

关于java - 减去字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20332013/

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