Using scanner.next() outside loop yields weird results
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
add a comment |
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
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
add a comment |
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
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
java loops
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
add a comment |
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
add a comment |
2 Answers
2
active
oldest
votes
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
you scan for a word:
String word = keyboard.next();
You print it:
printStem(word);
You enter into a while loop which waits until you give some input:
keyboard.hasNext()
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.
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.
add a comment |
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.
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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
you scan for a word:
String word = keyboard.next();
You print it:
printStem(word);
You enter into a while loop which waits until you give some input:
keyboard.hasNext()
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.
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.
add a comment |
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
you scan for a word:
String word = keyboard.next();
You print it:
printStem(word);
You enter into a while loop which waits until you give some input:
keyboard.hasNext()
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.
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.
add a comment |
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
you scan for a word:
String word = keyboard.next();
You print it:
printStem(word);
You enter into a while loop which waits until you give some input:
keyboard.hasNext()
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.
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.
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
you scan for a word:
String word = keyboard.next();
You print it:
printStem(word);
You enter into a while loop which waits until you give some input:
keyboard.hasNext()
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.
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.
answered Nov 20 at 11:17
abj1305
16510
16510
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Nov 20 at 11:10
community wiki
Michael
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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