-4

I have a String that accepts numbers from user input and I want to calculate the sum of all the numbers in a String.

An example of a sample output will look like this,

Enter an integer: 1234 The sum is 10.

Brandon
  • 27
  • 2
  • We dont provide code! Why not try it yourself? – Abhi Sep 28 '14 at 09:31
  • How about showing the code you've written and asking a specific question about what you think is not working in it? – William Price Sep 28 '14 at 09:31
  • Java 8: `string.chars().sum()-'0'*string.length()`. Of course you should verify that the input is valid first, e.g. `string.matches("[0-9]+")`. – Holger Sep 28 '14 at 10:11

1 Answers1

0
String s = JOptionPane.showInputDialog("Enter an integer");
int sum = 0;
for(int i = 0; i < s.lentgth(); i++){
   sum+=Integer.parseInt(s.charAt(i)+"");
}
System.out.println("Sum is: " + sum);
Yoda
  • 17,363
  • 67
  • 204
  • 344
  • 1
    There is not a method called parse() in the class Integer. Perhaps you mean parseInt() ? – Alboz Sep 28 '14 at 09:49
  • @Alboz What the is wrong with the answer. Answer is correct, the only reason you downvote it is that the guy who asked is lazy. – Yoda Sep 28 '14 at 10:19