简体   繁体   English

如何在while循环内增加charAt值

[英]How to increase charAt value inside a while loop

I'm trying to find a way to increase a value that is using charAt, but want to be able to update it while inside a while loop. 我正在尝试找到一种方法来增加使用charAt的值,但希望能够在while循环内进行更新。 Below is the current code that I have. 下面是我当前的代码。 I have tried recreating the variable inside of the loop and adding ++ to the end to increase the value, but I receive unexpected type errors. 我尝试在循环内部重新创建变量,并在末尾添加++以增加值,但是我收到意外的类型错误。

I am trying to have it take a value that you enter (ie 3124) and concatenate each value and then add them together. 我试图让它接受您输入的值(即3124)并连接每个值,然后将它们加在一起。 So based on the example, it would give a value of 10. 因此,基于该示例,它的值为10。

public static void main(String[] args) {

int Num, counter, i;
String str1;


str1 = JOptionPane.showInputDialog("Enter any number: ");
Num = str1.length();

counter = 0;
i = Integer.parseInt(Character.toString(str1.charAt(0)));
NumTot = 0;

while (counter <= Num)
{
  NumTot = i;
  counter++;
  i = Integer.parseInt(Character.toString(str1.charAt(0++)));
  }

     System.exit(0);
}

Idea: 理念:

  • Take in an integer 取一个整数
  • Use mod 10 to extract digit by digit 使用mod 10逐位提取数字

Example code: 示例代码:

public class IntegerSum {

    public static void main(String[] args) {

        int i = 3124;
        int sum = 0;
        while (i > 0) {
            sum += i % 10;
            i /= 10;
        }
        System.out.println("Sum: " + sum);
    }
}

Output: 输出:

Sum: 10


Note: My answer is based on your requirement of "I am trying to have it take a value that you enter (ie 3124) and concatenate each value and then add them together. So based on the example, it would give a value of 10." 注意:我的回答是基于您的要求“我正在尝试让它输入一个值(即3124),然后将每个值连接起来,然后将它们相加。因此,根据示例,它的值为10 。”

Some modifications to your program : 对您的程序进行了一些修改:

public static void main (String[] args) throws java.lang.Exception
{
    int Num, counter, i;
    String str1;
    int NumTot = 0;

    str1 = "3124";
    Num = str1.length();

    counter = 0;
    while (counter < Num)
    {


        i = Integer.parseInt(Character.toString(str1.charAt(counter)));
        NumTot = NumTot + i;
        counter++;
    }



  System.out.println(NumTot);
}

Here's a working version 这是一个工作版本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM