There is a logic error in a simple counting algorithm in my java codeHow to avoid Java code in JSP files?Can't start Eclipse - Java was started but returned exit code=13How can I “delimit” an integer from a given string?What is the difference between canonical name, simple name and class name in Java Class?How to read characters in a string in javaCount the number of occurrencesWhy is executing Java code in comments with certain Unicode characters allowed?I/P-a string S.O/P: For each digit start from 0-9,print count of their occurrence in S.Print10 lines,each line contain 2 space separated integersHow to print a line and type input in the same lineWould it make any difference giving arguments using scanner class instead of command line arguments?

Is there a rule that prohibits us from using 2 possessives in a row?

Rotated Position of Integers

If Sweden was to magically float away, at what altitude would it be visible from the southern hemisphere?

Bringing Food from Hometown for Out-of-Town Interview?

How can I offer a test ride while selling a bike?

How was Apollo supposed to rendezvous in the case of a lunar abort?

Is it possible to kill all life on Earth?

The term for the person/group a political party aligns themselves with to appear concerned about the general public

If a massive object like Jupiter flew past the Earth how close would it need to come to pull people off of the surface?

Why does my electric oven present the option of 40A and 50A breakers?

Why does the UK have more political parties than the US?

Starting VLC from command line always puts the window behind other windows

What is the difference between a game ban and a VAC ban in Steam?

arcpy.GetParameterAsText not passing arguments to script?

Do adult Russians normally hand-write Cyrillic as cursive or as block letters?

Can an old DSLR be upgraded to match modern smartphone image quality

Can you use a concentration spell while using Mantle of Majesty?

Opposite of "Squeaky wheel gets the grease"

California: "For quality assurance, this phone call is being recorded"

When was the word "ambigu" first used with the sense of "meal with all items served at the same time"?

Parsing CSV with AWK to Produce HTML Output

What if you don't bring your credit card or debit for incidentals?

Why use water tanks from a retired Space Shuttle?

How crucial is a waifu game storyline?



There is a logic error in a simple counting algorithm in my java code


How to avoid Java code in JSP files?Can't start Eclipse - Java was started but returned exit code=13How can I “delimit” an integer from a given string?What is the difference between canonical name, simple name and class name in Java Class?How to read characters in a string in javaCount the number of occurrencesWhy is executing Java code in comments with certain Unicode characters allowed?I/P-a string S.O/P: For each digit start from 0-9,print count of their occurrence in S.Print10 lines,each line contain 2 space separated integersHow to print a line and type input in the same lineWould it make any difference giving arguments using scanner class instead of command line arguments?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








-1















So there is a logic error inside my simple java counting words, first of in cmd, it's asking me to type the string twice, when it should show once



I run this in cmd, here is the output:



C:UsersMeDocuments>java count
shapeshifting
shapeshifting
Number of Occurrence of s is 2 in string shapeshifting
s
2


import java.util.Scanner;
public class count5

public static void main(String[] args)
Scanner input = new Scanner(System.in);
String str = input.nextLine();

char key = input.nextLine().charAt(0);
countString(str, key);


public static void countString(String str, char key)
int count = 0;
for (int i = 0; i < str.length(); i++)
if (str.charAt(i) == key)
count++;

System.out.println("Number of Occurrence of "
+ key + " is " + count + " in string " + str);

for (int i = 0; i < count; i++)
System.out.println(key);


if (count > 0)
System.out.println(count);





So here some thing that confuses me:



  1. why is there 3 lines needed allow user to type an input. I thought the previous line already let me enter the input. What is char key = input.nextLine().charAt(0); needed for, and the previous line? Shouldn't there be only input entering line?


  2. Why is there 2 for loops inside the code, don't they do same thing?










share|improve this question



















  • 1





    "Why is there 2 for loops inside the code", this is your code so why are you asking this?

    – Joakim Danielson
    Mar 24 at 11:02











  • 1. What is char key = input.nextLine().charAt(0); needed for : it is getting the first character of the input, thought change it to char key = str.charAt(0); 2. Why is there 2 for loops inside the code, don't they do same thing? .. the first loop is checking if there is match for the first letter form the string, and the second loop is printing the match found the same number of times.

    – VSB
    Mar 24 at 11:02












  • @VinodSinghBist can you write a full answer and I will accept it?

    – javalover
    Mar 24 at 11:07











  • @javalover please check below, and let me know if that works for you

    – VSB
    Mar 24 at 11:09











  • @VinodSinghBist thank you! so one last thing, String str = input.nextLine(); is just to make the input into string and then display at the next line? Is there way to combine the two line into one? Scanner input and string str = input.nextLine():?

    – javalover
    Mar 24 at 11:13

















-1















So there is a logic error inside my simple java counting words, first of in cmd, it's asking me to type the string twice, when it should show once



I run this in cmd, here is the output:



C:UsersMeDocuments>java count
shapeshifting
shapeshifting
Number of Occurrence of s is 2 in string shapeshifting
s
2


import java.util.Scanner;
public class count5

public static void main(String[] args)
Scanner input = new Scanner(System.in);
String str = input.nextLine();

char key = input.nextLine().charAt(0);
countString(str, key);


public static void countString(String str, char key)
int count = 0;
for (int i = 0; i < str.length(); i++)
if (str.charAt(i) == key)
count++;

System.out.println("Number of Occurrence of "
+ key + " is " + count + " in string " + str);

for (int i = 0; i < count; i++)
System.out.println(key);


if (count > 0)
System.out.println(count);





So here some thing that confuses me:



  1. why is there 3 lines needed allow user to type an input. I thought the previous line already let me enter the input. What is char key = input.nextLine().charAt(0); needed for, and the previous line? Shouldn't there be only input entering line?


  2. Why is there 2 for loops inside the code, don't they do same thing?










share|improve this question



















  • 1





    "Why is there 2 for loops inside the code", this is your code so why are you asking this?

    – Joakim Danielson
    Mar 24 at 11:02











  • 1. What is char key = input.nextLine().charAt(0); needed for : it is getting the first character of the input, thought change it to char key = str.charAt(0); 2. Why is there 2 for loops inside the code, don't they do same thing? .. the first loop is checking if there is match for the first letter form the string, and the second loop is printing the match found the same number of times.

    – VSB
    Mar 24 at 11:02












  • @VinodSinghBist can you write a full answer and I will accept it?

    – javalover
    Mar 24 at 11:07











  • @javalover please check below, and let me know if that works for you

    – VSB
    Mar 24 at 11:09











  • @VinodSinghBist thank you! so one last thing, String str = input.nextLine(); is just to make the input into string and then display at the next line? Is there way to combine the two line into one? Scanner input and string str = input.nextLine():?

    – javalover
    Mar 24 at 11:13













-1












-1








-1








So there is a logic error inside my simple java counting words, first of in cmd, it's asking me to type the string twice, when it should show once



I run this in cmd, here is the output:



C:UsersMeDocuments>java count
shapeshifting
shapeshifting
Number of Occurrence of s is 2 in string shapeshifting
s
2


import java.util.Scanner;
public class count5

public static void main(String[] args)
Scanner input = new Scanner(System.in);
String str = input.nextLine();

char key = input.nextLine().charAt(0);
countString(str, key);


public static void countString(String str, char key)
int count = 0;
for (int i = 0; i < str.length(); i++)
if (str.charAt(i) == key)
count++;

System.out.println("Number of Occurrence of "
+ key + " is " + count + " in string " + str);

for (int i = 0; i < count; i++)
System.out.println(key);


if (count > 0)
System.out.println(count);





So here some thing that confuses me:



  1. why is there 3 lines needed allow user to type an input. I thought the previous line already let me enter the input. What is char key = input.nextLine().charAt(0); needed for, and the previous line? Shouldn't there be only input entering line?


  2. Why is there 2 for loops inside the code, don't they do same thing?










share|improve this question
















So there is a logic error inside my simple java counting words, first of in cmd, it's asking me to type the string twice, when it should show once



I run this in cmd, here is the output:



C:UsersMeDocuments>java count
shapeshifting
shapeshifting
Number of Occurrence of s is 2 in string shapeshifting
s
2


import java.util.Scanner;
public class count5

public static void main(String[] args)
Scanner input = new Scanner(System.in);
String str = input.nextLine();

char key = input.nextLine().charAt(0);
countString(str, key);


public static void countString(String str, char key)
int count = 0;
for (int i = 0; i < str.length(); i++)
if (str.charAt(i) == key)
count++;

System.out.println("Number of Occurrence of "
+ key + " is " + count + " in string " + str);

for (int i = 0; i < count; i++)
System.out.println(key);


if (count > 0)
System.out.println(count);





So here some thing that confuses me:



  1. why is there 3 lines needed allow user to type an input. I thought the previous line already let me enter the input. What is char key = input.nextLine().charAt(0); needed for, and the previous line? Shouldn't there be only input entering line?


  2. Why is there 2 for loops inside the code, don't they do same thing?







java count






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 24 at 10:59









Ivar

3,026113344




3,026113344










asked Mar 24 at 10:57









javaloverjavalover

31




31







  • 1





    "Why is there 2 for loops inside the code", this is your code so why are you asking this?

    – Joakim Danielson
    Mar 24 at 11:02











  • 1. What is char key = input.nextLine().charAt(0); needed for : it is getting the first character of the input, thought change it to char key = str.charAt(0); 2. Why is there 2 for loops inside the code, don't they do same thing? .. the first loop is checking if there is match for the first letter form the string, and the second loop is printing the match found the same number of times.

    – VSB
    Mar 24 at 11:02












  • @VinodSinghBist can you write a full answer and I will accept it?

    – javalover
    Mar 24 at 11:07











  • @javalover please check below, and let me know if that works for you

    – VSB
    Mar 24 at 11:09











  • @VinodSinghBist thank you! so one last thing, String str = input.nextLine(); is just to make the input into string and then display at the next line? Is there way to combine the two line into one? Scanner input and string str = input.nextLine():?

    – javalover
    Mar 24 at 11:13












  • 1





    "Why is there 2 for loops inside the code", this is your code so why are you asking this?

    – Joakim Danielson
    Mar 24 at 11:02











  • 1. What is char key = input.nextLine().charAt(0); needed for : it is getting the first character of the input, thought change it to char key = str.charAt(0); 2. Why is there 2 for loops inside the code, don't they do same thing? .. the first loop is checking if there is match for the first letter form the string, and the second loop is printing the match found the same number of times.

    – VSB
    Mar 24 at 11:02












  • @VinodSinghBist can you write a full answer and I will accept it?

    – javalover
    Mar 24 at 11:07











  • @javalover please check below, and let me know if that works for you

    – VSB
    Mar 24 at 11:09











  • @VinodSinghBist thank you! so one last thing, String str = input.nextLine(); is just to make the input into string and then display at the next line? Is there way to combine the two line into one? Scanner input and string str = input.nextLine():?

    – javalover
    Mar 24 at 11:13







1




1





"Why is there 2 for loops inside the code", this is your code so why are you asking this?

– Joakim Danielson
Mar 24 at 11:02





"Why is there 2 for loops inside the code", this is your code so why are you asking this?

– Joakim Danielson
Mar 24 at 11:02













1. What is char key = input.nextLine().charAt(0); needed for : it is getting the first character of the input, thought change it to char key = str.charAt(0); 2. Why is there 2 for loops inside the code, don't they do same thing? .. the first loop is checking if there is match for the first letter form the string, and the second loop is printing the match found the same number of times.

– VSB
Mar 24 at 11:02






1. What is char key = input.nextLine().charAt(0); needed for : it is getting the first character of the input, thought change it to char key = str.charAt(0); 2. Why is there 2 for loops inside the code, don't they do same thing? .. the first loop is checking if there is match for the first letter form the string, and the second loop is printing the match found the same number of times.

– VSB
Mar 24 at 11:02














@VinodSinghBist can you write a full answer and I will accept it?

– javalover
Mar 24 at 11:07





@VinodSinghBist can you write a full answer and I will accept it?

– javalover
Mar 24 at 11:07













@javalover please check below, and let me know if that works for you

– VSB
Mar 24 at 11:09





@javalover please check below, and let me know if that works for you

– VSB
Mar 24 at 11:09













@VinodSinghBist thank you! so one last thing, String str = input.nextLine(); is just to make the input into string and then display at the next line? Is there way to combine the two line into one? Scanner input and string str = input.nextLine():?

– javalover
Mar 24 at 11:13





@VinodSinghBist thank you! so one last thing, String str = input.nextLine(); is just to make the input into string and then display at the next line? Is there way to combine the two line into one? Scanner input and string str = input.nextLine():?

– javalover
Mar 24 at 11:13












1 Answer
1






active

oldest

votes


















1














Try this solution which should ask for one time input and traverse the complete input string entered for the match



import java.util.Scanner; 

public class stringCompair

public static void main(String[] args)
Scanner input = new Scanner(System.in);
String str = input.nextLine();
for(int i=0 ; i < str.length();i++)
char key = str.charAt(i);
countString(str, key);




public static void countString(String str, char key)
int count = 0;
for (int i = 0; i < str.length(); i++)
if (str.charAt(i) == key)
count++;

System.out.println("Number of Occurrence of "
+ key + " is " + count + " in string " + str);







share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55323085%2fthere-is-a-logic-error-in-a-simple-counting-algorithm-in-my-java-code%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Try this solution which should ask for one time input and traverse the complete input string entered for the match



    import java.util.Scanner; 

    public class stringCompair

    public static void main(String[] args)
    Scanner input = new Scanner(System.in);
    String str = input.nextLine();
    for(int i=0 ; i < str.length();i++)
    char key = str.charAt(i);
    countString(str, key);




    public static void countString(String str, char key)
    int count = 0;
    for (int i = 0; i < str.length(); i++)
    if (str.charAt(i) == key)
    count++;

    System.out.println("Number of Occurrence of "
    + key + " is " + count + " in string " + str);







    share|improve this answer



























      1














      Try this solution which should ask for one time input and traverse the complete input string entered for the match



      import java.util.Scanner; 

      public class stringCompair

      public static void main(String[] args)
      Scanner input = new Scanner(System.in);
      String str = input.nextLine();
      for(int i=0 ; i < str.length();i++)
      char key = str.charAt(i);
      countString(str, key);




      public static void countString(String str, char key)
      int count = 0;
      for (int i = 0; i < str.length(); i++)
      if (str.charAt(i) == key)
      count++;

      System.out.println("Number of Occurrence of "
      + key + " is " + count + " in string " + str);







      share|improve this answer

























        1












        1








        1







        Try this solution which should ask for one time input and traverse the complete input string entered for the match



        import java.util.Scanner; 

        public class stringCompair

        public static void main(String[] args)
        Scanner input = new Scanner(System.in);
        String str = input.nextLine();
        for(int i=0 ; i < str.length();i++)
        char key = str.charAt(i);
        countString(str, key);




        public static void countString(String str, char key)
        int count = 0;
        for (int i = 0; i < str.length(); i++)
        if (str.charAt(i) == key)
        count++;

        System.out.println("Number of Occurrence of "
        + key + " is " + count + " in string " + str);







        share|improve this answer













        Try this solution which should ask for one time input and traverse the complete input string entered for the match



        import java.util.Scanner; 

        public class stringCompair

        public static void main(String[] args)
        Scanner input = new Scanner(System.in);
        String str = input.nextLine();
        for(int i=0 ; i < str.length();i++)
        char key = str.charAt(i);
        countString(str, key);




        public static void countString(String str, char key)
        int count = 0;
        for (int i = 0; i < str.length(); i++)
        if (str.charAt(i) == key)
        count++;

        System.out.println("Number of Occurrence of "
        + key + " is " + count + " in string " + str);








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 24 at 11:08









        VSBVSB

        25229




        25229



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55323085%2fthere-is-a-logic-error-in-a-simple-counting-algorithm-in-my-java-code%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript