0

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 (i.e. 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);
}
user2141482
  • 15
  • 1
  • 3
  • You are probably being asked to look at string iteration http://stackoverflow.com/questions/196830/what-is-the-easiest-best-most-correct-way-to-iterate-through-the-characters-of-a – Mindeater Jun 03 '15 at 03:04

2 Answers2

2

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 (i.e. 3124) and concatenate each value and then add them together. So based on the example, it would give a value of 10."

almightyGOSU
  • 3,731
  • 6
  • 31
  • 41
0

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

Polynomial Proton
  • 5,020
  • 20
  • 37