Using scanner.next() outside loop yields weird results












-1














Recently a friend of mine showed me her code seeking my advice on why it wouldn't work. Her original code was this:



public static void printStem(String word) ...

public static void main(String args)
{

Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the words: ");
String word = keyboard.next();
printStem(word);

while (keyboard.hasNext())
{
printStem(word);
word = keybord.next();
}
}


This will yield really weird results. It will ask the user twice, then executes printStem twice (which might be expected), and after that goes ahead and always prints only the first entered corpus (word).



Eventually I figured out that it would work as expected when removing the keyboard.next() from outside the loop like so



public static void printStem(String word) ...

public static void main(String args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the words: ");

while (keyboard.hasNext())
{
String word = keybord.next();
printStem(word);
}
}


When asked why this would be I had no plausible explanation, as this should behave identical. My best guess is that something must be smelly with hasNext() but I couldn't figure out why exactly. So. What is going on here? Any explanation is appreciated :)










share|improve this question
























  • Thanks @Michael I corrected the mentioned issues. However printStem does really only output stuff via System.out.println so it's not much worth mentioning here.
    – Fohlen
    Nov 20 at 12:05






  • 1




    It is worth mentioning. I should be able to copy and paste your code in my IDE to work out problem and not have to mess around.
    – Michael
    Nov 20 at 12:06
















-1














Recently a friend of mine showed me her code seeking my advice on why it wouldn't work. Her original code was this:



public static void printStem(String word) ...

public static void main(String args)
{

Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the words: ");
String word = keyboard.next();
printStem(word);

while (keyboard.hasNext())
{
printStem(word);
word = keybord.next();
}
}


This will yield really weird results. It will ask the user twice, then executes printStem twice (which might be expected), and after that goes ahead and always prints only the first entered corpus (word).



Eventually I figured out that it would work as expected when removing the keyboard.next() from outside the loop like so



public static void printStem(String word) ...

public static void main(String args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the words: ");

while (keyboard.hasNext())
{
String word = keybord.next();
printStem(word);
}
}


When asked why this would be I had no plausible explanation, as this should behave identical. My best guess is that something must be smelly with hasNext() but I couldn't figure out why exactly. So. What is going on here? Any explanation is appreciated :)










share|improve this question
























  • Thanks @Michael I corrected the mentioned issues. However printStem does really only output stuff via System.out.println so it's not much worth mentioning here.
    – Fohlen
    Nov 20 at 12:05






  • 1




    It is worth mentioning. I should be able to copy and paste your code in my IDE to work out problem and not have to mess around.
    – Michael
    Nov 20 at 12:06














-1












-1








-1







Recently a friend of mine showed me her code seeking my advice on why it wouldn't work. Her original code was this:



public static void printStem(String word) ...

public static void main(String args)
{

Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the words: ");
String word = keyboard.next();
printStem(word);

while (keyboard.hasNext())
{
printStem(word);
word = keybord.next();
}
}


This will yield really weird results. It will ask the user twice, then executes printStem twice (which might be expected), and after that goes ahead and always prints only the first entered corpus (word).



Eventually I figured out that it would work as expected when removing the keyboard.next() from outside the loop like so



public static void printStem(String word) ...

public static void main(String args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the words: ");

while (keyboard.hasNext())
{
String word = keybord.next();
printStem(word);
}
}


When asked why this would be I had no plausible explanation, as this should behave identical. My best guess is that something must be smelly with hasNext() but I couldn't figure out why exactly. So. What is going on here? Any explanation is appreciated :)










share|improve this question















Recently a friend of mine showed me her code seeking my advice on why it wouldn't work. Her original code was this:



public static void printStem(String word) ...

public static void main(String args)
{

Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the words: ");
String word = keyboard.next();
printStem(word);

while (keyboard.hasNext())
{
printStem(word);
word = keybord.next();
}
}


This will yield really weird results. It will ask the user twice, then executes printStem twice (which might be expected), and after that goes ahead and always prints only the first entered corpus (word).



Eventually I figured out that it would work as expected when removing the keyboard.next() from outside the loop like so



public static void printStem(String word) ...

public static void main(String args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the words: ");

while (keyboard.hasNext())
{
String word = keybord.next();
printStem(word);
}
}


When asked why this would be I had no plausible explanation, as this should behave identical. My best guess is that something must be smelly with hasNext() but I couldn't figure out why exactly. So. What is going on here? Any explanation is appreciated :)







java loops






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 at 12:06

























asked Nov 20 at 11:00









Fohlen

59110




59110












  • Thanks @Michael I corrected the mentioned issues. However printStem does really only output stuff via System.out.println so it's not much worth mentioning here.
    – Fohlen
    Nov 20 at 12:05






  • 1




    It is worth mentioning. I should be able to copy and paste your code in my IDE to work out problem and not have to mess around.
    – Michael
    Nov 20 at 12:06


















  • Thanks @Michael I corrected the mentioned issues. However printStem does really only output stuff via System.out.println so it's not much worth mentioning here.
    – Fohlen
    Nov 20 at 12:05






  • 1




    It is worth mentioning. I should be able to copy and paste your code in my IDE to work out problem and not have to mess around.
    – Michael
    Nov 20 at 12:06
















Thanks @Michael I corrected the mentioned issues. However printStem does really only output stuff via System.out.println so it's not much worth mentioning here.
– Fohlen
Nov 20 at 12:05




Thanks @Michael I corrected the mentioned issues. However printStem does really only output stuff via System.out.println so it's not much worth mentioning here.
– Fohlen
Nov 20 at 12:05




1




1




It is worth mentioning. I should be able to copy and paste your code in my IDE to work out problem and not have to mess around.
– Michael
Nov 20 at 12:06




It is worth mentioning. I should be able to copy and paste your code in my IDE to work out problem and not have to mess around.
– Michael
Nov 20 at 12:06












2 Answers
2






active

oldest

votes


















2














Some explanation about hasNext():



Returns true if this scanner has another token in its input. 
This method may block while waiting for input to scan.
The scanner does not advance past any input.


In your first piece of code





  1. you scan for a word: String word = keyboard.next();


  2. You print it: printStem(word);


  3. You enter into a while loop which waits until you give some input: keyboard.hasNext()


  4. In step 3 you take the input but never store it in String word and you print it. Naturally previous value of word will be printed.


  5. Then you do a next read by next().





Explanation for next():



Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.



Hence you get a weird behavior.






share|improve this answer





























    0















    This will yield really weird results




    Yeah, because the logic is wrong.



    You get the input



    String word = keyboard.next(); 


    print it



    printStem(word);


    then print it again, and ask for another word:



    while (keyboard.hasNext())
    {
    printStem(word);
    word = keybord.next();
    }


    So every time you loop you print the word they entered last time, rather than the word they entered this time. You just need to swap the two lines in the while-loop, which then makes the keyboard.next() and printStem(word) outside of the loop body redundant.




    as this should behave identical




    No it shouldn't. You reversed the order of operations in the while-loop body.






    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%2f53391534%2fusing-scanner-next-outside-loop-yields-weird-results%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      Some explanation about hasNext():



      Returns true if this scanner has another token in its input. 
      This method may block while waiting for input to scan.
      The scanner does not advance past any input.


      In your first piece of code





      1. you scan for a word: String word = keyboard.next();


      2. You print it: printStem(word);


      3. You enter into a while loop which waits until you give some input: keyboard.hasNext()


      4. In step 3 you take the input but never store it in String word and you print it. Naturally previous value of word will be printed.


      5. Then you do a next read by next().





      Explanation for next():



      Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.



      Hence you get a weird behavior.






      share|improve this answer


























        2














        Some explanation about hasNext():



        Returns true if this scanner has another token in its input. 
        This method may block while waiting for input to scan.
        The scanner does not advance past any input.


        In your first piece of code





        1. you scan for a word: String word = keyboard.next();


        2. You print it: printStem(word);


        3. You enter into a while loop which waits until you give some input: keyboard.hasNext()


        4. In step 3 you take the input but never store it in String word and you print it. Naturally previous value of word will be printed.


        5. Then you do a next read by next().





        Explanation for next():



        Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.



        Hence you get a weird behavior.






        share|improve this answer
























          2












          2








          2






          Some explanation about hasNext():



          Returns true if this scanner has another token in its input. 
          This method may block while waiting for input to scan.
          The scanner does not advance past any input.


          In your first piece of code





          1. you scan for a word: String word = keyboard.next();


          2. You print it: printStem(word);


          3. You enter into a while loop which waits until you give some input: keyboard.hasNext()


          4. In step 3 you take the input but never store it in String word and you print it. Naturally previous value of word will be printed.


          5. Then you do a next read by next().





          Explanation for next():



          Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.



          Hence you get a weird behavior.






          share|improve this answer












          Some explanation about hasNext():



          Returns true if this scanner has another token in its input. 
          This method may block while waiting for input to scan.
          The scanner does not advance past any input.


          In your first piece of code





          1. you scan for a word: String word = keyboard.next();


          2. You print it: printStem(word);


          3. You enter into a while loop which waits until you give some input: keyboard.hasNext()


          4. In step 3 you take the input but never store it in String word and you print it. Naturally previous value of word will be printed.


          5. Then you do a next read by next().





          Explanation for next():



          Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.



          Hence you get a weird behavior.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 20 at 11:17









          abj1305

          16510




          16510

























              0















              This will yield really weird results




              Yeah, because the logic is wrong.



              You get the input



              String word = keyboard.next(); 


              print it



              printStem(word);


              then print it again, and ask for another word:



              while (keyboard.hasNext())
              {
              printStem(word);
              word = keybord.next();
              }


              So every time you loop you print the word they entered last time, rather than the word they entered this time. You just need to swap the two lines in the while-loop, which then makes the keyboard.next() and printStem(word) outside of the loop body redundant.




              as this should behave identical




              No it shouldn't. You reversed the order of operations in the while-loop body.






              share|improve this answer




























                0















                This will yield really weird results




                Yeah, because the logic is wrong.



                You get the input



                String word = keyboard.next(); 


                print it



                printStem(word);


                then print it again, and ask for another word:



                while (keyboard.hasNext())
                {
                printStem(word);
                word = keybord.next();
                }


                So every time you loop you print the word they entered last time, rather than the word they entered this time. You just need to swap the two lines in the while-loop, which then makes the keyboard.next() and printStem(word) outside of the loop body redundant.




                as this should behave identical




                No it shouldn't. You reversed the order of operations in the while-loop body.






                share|improve this answer


























                  0












                  0








                  0







                  This will yield really weird results




                  Yeah, because the logic is wrong.



                  You get the input



                  String word = keyboard.next(); 


                  print it



                  printStem(word);


                  then print it again, and ask for another word:



                  while (keyboard.hasNext())
                  {
                  printStem(word);
                  word = keybord.next();
                  }


                  So every time you loop you print the word they entered last time, rather than the word they entered this time. You just need to swap the two lines in the while-loop, which then makes the keyboard.next() and printStem(word) outside of the loop body redundant.




                  as this should behave identical




                  No it shouldn't. You reversed the order of operations in the while-loop body.






                  share|improve this answer















                  This will yield really weird results




                  Yeah, because the logic is wrong.



                  You get the input



                  String word = keyboard.next(); 


                  print it



                  printStem(word);


                  then print it again, and ask for another word:



                  while (keyboard.hasNext())
                  {
                  printStem(word);
                  word = keybord.next();
                  }


                  So every time you loop you print the word they entered last time, rather than the word they entered this time. You just need to swap the two lines in the while-loop, which then makes the keyboard.next() and printStem(word) outside of the loop body redundant.




                  as this should behave identical




                  No it shouldn't. You reversed the order of operations in the while-loop body.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  answered Nov 20 at 11:10


























                  community wiki





                  Michael































                      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.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • 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%2f53391534%2fusing-scanner-next-outside-loop-yields-weird-results%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

                      Create new schema in PostgreSQL using DBeaver

                      Deepest pit of an array with Javascript: test on Codility

                      Costa Masnaga