简体   繁体   中英

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. 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. So based on the example, it would give a value of 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

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."

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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