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.

Results 1 to 3 of 3

Thread: how can count

  1. #1
    Junior Member
    Join Date
    Sep 2017
    Posts
    10
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Unhappy how can count

    how can i count in example the numbers of 1's in 101e
    the answer should be 2

  2. #2
    Junior Member
    Join Date
    Oct 2017
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: how can count

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

  3. #3
    Junior Member
    Join Date
    Sep 2017
    Posts
    10
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: how can count

    think you

Similar Threads

  1. Replies: 10
    Last Post: July 1st, 2014, 02:41 PM
  2. Count out program
    By javaman1 in forum Java Theory & Questions
    Replies: 1
    Last Post: June 21st, 2014, 03:25 AM
  3. Column count doesn't match value count at row 1
    By Tyluur in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 30th, 2012, 01:31 AM
  4. How to Count the CAPS
    By Sean137 in forum Java Theory & Questions
    Replies: 1
    Last Post: December 14th, 2010, 08:30 AM
  5. select count(*)
    By jacinto in forum JDBC & Databases
    Replies: 4
    Last Post: March 2nd, 2010, 10:30 PM