how can i count in example the numbers of 1's in 101e
the answer should be 2
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
how can i count in example the numbers of 1's in 101e
the answer should be 2
public class Main { public static void main(String[] args) { String string1 = "10010101010101"; int sum = 0; for (int index = 0; index < string1.length(); index++) { char aChar = string1.charAt(index); if (aChar == '1') { sum =sum +1; } } System.out.println(sum); } }
You define your string of choice, named string1, you define a counter sum, and then you parse your string character by character and compare it to 1. If 1st character is = 1, then sum =1 else sum = 0, if second character is =1 you add one to sum, or else zero, and you keep doing that inside a for loop, until you reach the end of your string (in other words the last character, whos posistion is equal to strings length).[COLOR="Silver"]
think you