I'm having problems removing an element from the queue. through extensive debugging I found that all the elements are being added, but when I try to remove one, it gives me the same element over and over. here is the code:
private synchronized String accessMyQueue(char[] myInput) {
String myOutput="";
myOutput=convertToString(myQueue.remove());
System.out.println("accessqueue removing:" + myOutput);
}
//and so you can see what's going on in convertToString...
private String convertToString(char[] a) {
String myString = new String(a);
return myString.trim();
}
If myQueue is an instance of a standard Java class implementing the Queue interface, the chance that you have found a bug with it are ... well, close enough to zero that we can discount it as a possibility.
If, on the other hand, you've implemented your own queue then, yes, there may well be a problem but, since psychic debugging is not yet a well-established field of endeavour, you're going to have to show us the code for it :-)
I see one of two possibilities. The first is that you are somehow setting each node of your queue to the same value and you may well be removing items okay (you can detect this by adding one item then trying to remove two). This is far more likely in a language like C where you may inadvertently reuse the same pointer but it's far less likely in Java with its improved strings.
The second and most likely is that you're not removing the element from the queue when you call remove, rather you're returning the string without adjusting whatever your underlying data structure is (or, alternatively, adjusting it wrongly).
Short of seeing the code, that's about as good as I can do.
After your update that you were indeed using LinkedList, I thought I'd give it a shot with a very simple example xx.java:
import java.util.LinkedList;
import java.util.Queue;
public class xx {
public static void main (String args[]) {
Queue<String> myQueue = new LinkedList<String>();
myQueue.add ("abc");
myQueue.add ("def");
System.out.println (myQueue.size());
System.out.println (myQueue.remove());
System.out.println (myQueue.size());
System.out.println (myQueue.remove());
System.out.println (myQueue.size());
try {
System.out.println (myQueue.remove());
} catch (Exception e) {
e.printStackTrace();
}
}
}
This outputs:
2
abc
1
def
0
java.util.NoSuchElementException
at java.util.LinkedList.remove(LinkedList.java:805)
at java.util.LinkedList.removeFirst(LinkedList.java:151)
at java.util.LinkedList.remove(LinkedList.java:498)
at xx.main(xx.java:14)
as expected.
So, bottom line is, I think we're going to need to see more of your code. It's difficult to conceive that, if there were a bug in LinkedList or the Queue interface, it wouldn't have been found yet by the millions of other users :-)
You also want to try putting the System.out.println (myQueue.size()); line at a few strategic places in your code to see what's happening with the queue. This may give you an indication as to what's going on.
Related
This is meant to be a canonical question/answer that can be used as a
duplicate target. These requirements are based on the most common
questions posted every day and may be added to as needed. They all
require the same basic code structure to get to each of the scenarios
and they are generally dependent on one another.
Scanner seems like a "simple" class to use, and that is where the first mistake is made. It is not simple, it has all kinds of non-obvious side effect and aberrant behaviors that break the Principle of Least Astonishment in very subtle ways.
So this might seem to be overkill for this class, but the peeling the onions errors and problems are all simple, but taken together they are very complex because of their interactions and side effects. This is why there are so many questions about it on Stack Overflow every day.
Common Scanner questions:
Most Scanner questions include failed attempts at more than one of these things.
I want to be able to have my program automatically wait for the next input after each previous input as well.
I want to know how to detect an exit command and end my program when that command is entered.
I want to know how to match multiple commands for the exit command in a case-insensitive way.
I want to be able to match regular expression patterns as well as the built-in primitives. For example, how to match what appears to be a date ( 2014/10/18 )?
I want to know how to match things that might not easily be implemented with regular expression matching - for example, an URL ( http://google.com ).
Motivation:
In the Java world, Scanner is a special case, it is an extremely finicky class that teachers should not give new students instructions to use. In most cases the instructors do not even know how to use it correctly. It is hardly if ever used in professional production code so its value to students is extremely questionable.
Using Scanner implies all the other things this question and answer mentions. It is never just about Scanner it is about how to solve these common problems with Scanner that are always co morbid problems in almost all the question that get Scanner wrong. It is never just about next() vs nextLine(), that is just a symptom of the finickiness of the implementation of the class, there are always other issues in the code posting in questions asking about Scanner.
The answer shows a complete, idiomatic implementation of 99% of cases where Scanner is used and asked about on StackOverflow.
Especially in beginner code. If you think this answer is too complex then complain to the instructors that tell new students to use Scanner before explaining the intricacies, quirks, non-obvious side effects and peculiarities of its behavior.
Scanner is the a great teaching moment about how important the Principle of least astonishment is and why consistent behavior and semantics are important in naming methods and method arguments.
Note to students:
You will probably never actually see Scanner used in
professional/commercial line of business apps because everything it
does is done better by something else. Real world software has to be
more resilient and maintainable than Scanner allows you to write
code. Real world software uses standardized file format parsers and
documented file formats, not the adhoc input formats that you are
given in stand alone assignments.
Idiomatic Example:
The following is how to properly use the java.util.Scanner class to interactively read user input from System.in correctly( sometimes referred to as stdin, especially in C, C++ and other languages as well as in Unix and Linux). It idiomatically demonstrates the most common things that are requested to be done.
package com.stackoverflow.scanner;
import javax.annotation.Nonnull;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.regex.Pattern;
import static java.lang.String.format;
public class ScannerExample
{
private static final Set<String> EXIT_COMMANDS;
private static final Set<String> HELP_COMMANDS;
private static final Pattern DATE_PATTERN;
private static final String HELP_MESSAGE;
static
{
final SortedSet<String> ecmds = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
ecmds.addAll(Arrays.asList("exit", "done", "quit", "end", "fino"));
EXIT_COMMANDS = Collections.unmodifiableSortedSet(ecmds);
final SortedSet<String> hcmds = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
hcmds.addAll(Arrays.asList("help", "helpi", "?"));
HELP_COMMANDS = Collections.unmodifiableSet(hcmds);
DATE_PATTERN = Pattern.compile("\\d{4}([-\\/])\\d{2}\\1\\d{2}"); // http://regex101.com/r/xB8dR3/1
HELP_MESSAGE = format("Please enter some data or enter one of the following commands to exit %s", EXIT_COMMANDS);
}
/**
* Using exceptions to control execution flow is always bad.
* That is why this is encapsulated in a method, this is done this
* way specifically so as not to introduce any external libraries
* so that this is a completely self contained example.
* #param s possible url
* #return true if s represents a valid url, false otherwise
*/
private static boolean isValidURL(#Nonnull final String s)
{
try { new URL(s); return true; }
catch (final MalformedURLException e) { return false; }
}
private static void output(#Nonnull final String format, #Nonnull final Object... args)
{
System.out.println(format(format, args));
}
public static void main(final String[] args)
{
final Scanner sis = new Scanner(System.in);
output(HELP_MESSAGE);
while (sis.hasNext())
{
if (sis.hasNextInt())
{
final int next = sis.nextInt();
output("You entered an Integer = %d", next);
}
else if (sis.hasNextLong())
{
final long next = sis.nextLong();
output("You entered a Long = %d", next);
}
else if (sis.hasNextDouble())
{
final double next = sis.nextDouble();
output("You entered a Double = %f", next);
}
else if (sis.hasNext("\\d+"))
{
final BigInteger next = sis.nextBigInteger();
output("You entered a BigInteger = %s", next);
}
else if (sis.hasNextBoolean())
{
final boolean next = sis.nextBoolean();
output("You entered a Boolean representation = %s", next);
}
else if (sis.hasNext(DATE_PATTERN))
{
final String next = sis.next(DATE_PATTERN);
output("You entered a Date representation = %s", next);
}
else // unclassified
{
final String next = sis.next();
if (isValidURL(next))
{
output("You entered a valid URL = %s", next);
}
else
{
if (EXIT_COMMANDS.contains(next))
{
output("Exit command %s issued, exiting!", next);
break;
}
else if (HELP_COMMANDS.contains(next)) { output(HELP_MESSAGE); }
else { output("You entered an unclassified String = %s", next); }
}
}
}
/*
This will close the underlying InputStream, in this case System.in, and free those resources.
WARNING: You will not be able to read from System.in anymore after you call .close().
If you wanted to use System.in for something else, then don't close the Scanner.
*/
sis.close();
System.exit(0);
}
}
Notes:
This may look like a lot of code, but it illustrates the minimum
effort needed to use the Scanner class correctly and not have to
deal with subtle bugs and side effects that plague those new to
programming and this terribly implemented class called
java.util.Scanner. It tries to illustrate what idiomatic Java code
should look like and behave like.
Below are some of the things I was thinking about when I wrote this example:
JDK Version:
I purposely kept this example compatible with JDK 6. If some scenario really demands a feature of JDK 7/8 I or someone else will post a new answer with specifics about how to modify this for that version JDK.
The majority of questions about this class come from students and they usually have restrictions on what they can use to solve a problem so I restricted this as much as I could to show how to do the common things without any other dependencies. In the 22+ years I have been working with Java and consulting the majority of that time I have never encountered professional use of this class in the 10's of millions of lines source code I have seen.
Processing commands:
This shows exactly how to idiomatically read commands from the user interactively and dispatch those commands. The majority of questions about java.util.Scanner are of the how can I get my program to quit when I enter some specific input category. This shows that clearly.
Naive Dispatcher
The dispatch logic is intentionally naive so as to not complicate the solution for new readers. A dispatcher based on a Strategy Pattern or Chain Of Responsibility pattern would be more appropriate for real world problems that would be much more complex.
Error Handling
The code was deliberately structured as to require no Exception handling because there is no scenario where some data might not be correct.
.hasNext() and .hasNextXxx()
I rarely see anyone using the .hasNext() properly, by testing for the generic .hasNext() to control the event loop, and then using the if(.hasNextXxx()) idiom lets you decide how and what to proceed with your code without having to worry about asking for an int when none is available, thus no exception handling code.
.nextXXX() vs .nextLine()
This is something that breaks everyone's code. It is a finicky detail that should not have to be dealt with and has a very obfusated bug that is hard to reason about because of it breaks the Principal of Least Astonishment
The .nextXXX() methods do not consume the line ending. .nextLine() does.
That means that calling .nextLine() immediately after .nextXXX() will just return the line ending. You have to call it again to actually get the next line.
This is why many people advocate either use nothing but the .nextXXX() methods or only .nextLine() but not both at the same time so that this finicky behavior does not trip you up. Personally I think the type safe methods are much better than having to then test and parse and catch errors manually.
Immutablity:
Notice that there are no mutable variables used in the code, this is important to learn how to do, it eliminates four of the most major sources of runtime errors and subtle bugs.
No nulls means no possibility of a NullPointerExceptions!
No mutability means that you don't have to worry about method arguments changing or anything else changing. When you step debug through you never have to use watch to see what variables are change to what values, if they are changing. This makes the logic 100% deterministic when you read it.
No mutability means your code is automatically thread-safe.
No side effects. If nothing can change, the you don't have to worry about some subtle side effect of some edge case changing something unexpectedly!
Read this if you don't understand how to apply the final keyword in your own code.
Using a Set instead of massive switch or if/elseif blocks:
Notice how I use a Set<String> and use .contains() to classify the commands instead of a massive switch or if/elseif monstrosity that would bloat your code and more importantly make maintenance a nightmare! Adding a new overloaded command is as simple as adding a new String to the array in the constructor.
This also would work very well with i18n and i10n and the proper ResourceBundles.
A Map<Locale,Set<String>> would let you have multiple language support with very little overhead!
#Nonnull
I have decided that all my code should explicitly declare if something is #Nonnull or #Nullable. It lets your IDE help warn you about potential NullPointerException hazards and when you do not have to check.
Most importantly it documents the expectation for future readers that none of these method parameters should be null.
Calling .close()
Really think about this one before you do it.
What do you think will happen System.in if you were to call sis.close()? See the comments in the listing above.
Please fork and send pull requests and I will update this question and answer for other basic usage scenarios.
This is meant to be a canonical question/answer that can be used as a
duplicate target. These requirements are based on the most common
questions posted every day and may be added to as needed. They all
require the same basic code structure to get to each of the scenarios
and they are generally dependent on one another.
Scanner seems like a "simple" class to use, and that is where the first mistake is made. It is not simple, it has all kinds of non-obvious side effect and aberrant behaviors that break the Principle of Least Astonishment in very subtle ways.
So this might seem to be overkill for this class, but the peeling the onions errors and problems are all simple, but taken together they are very complex because of their interactions and side effects. This is why there are so many questions about it on Stack Overflow every day.
Common Scanner questions:
Most Scanner questions include failed attempts at more than one of these things.
I want to be able to have my program automatically wait for the next input after each previous input as well.
I want to know how to detect an exit command and end my program when that command is entered.
I want to know how to match multiple commands for the exit command in a case-insensitive way.
I want to be able to match regular expression patterns as well as the built-in primitives. For example, how to match what appears to be a date ( 2014/10/18 )?
I want to know how to match things that might not easily be implemented with regular expression matching - for example, an URL ( http://google.com ).
Motivation:
In the Java world, Scanner is a special case, it is an extremely finicky class that teachers should not give new students instructions to use. In most cases the instructors do not even know how to use it correctly. It is hardly if ever used in professional production code so its value to students is extremely questionable.
Using Scanner implies all the other things this question and answer mentions. It is never just about Scanner it is about how to solve these common problems with Scanner that are always co morbid problems in almost all the question that get Scanner wrong. It is never just about next() vs nextLine(), that is just a symptom of the finickiness of the implementation of the class, there are always other issues in the code posting in questions asking about Scanner.
The answer shows a complete, idiomatic implementation of 99% of cases where Scanner is used and asked about on StackOverflow.
Especially in beginner code. If you think this answer is too complex then complain to the instructors that tell new students to use Scanner before explaining the intricacies, quirks, non-obvious side effects and peculiarities of its behavior.
Scanner is the a great teaching moment about how important the Principle of least astonishment is and why consistent behavior and semantics are important in naming methods and method arguments.
Note to students:
You will probably never actually see Scanner used in
professional/commercial line of business apps because everything it
does is done better by something else. Real world software has to be
more resilient and maintainable than Scanner allows you to write
code. Real world software uses standardized file format parsers and
documented file formats, not the adhoc input formats that you are
given in stand alone assignments.
Idiomatic Example:
The following is how to properly use the java.util.Scanner class to interactively read user input from System.in correctly( sometimes referred to as stdin, especially in C, C++ and other languages as well as in Unix and Linux). It idiomatically demonstrates the most common things that are requested to be done.
package com.stackoverflow.scanner;
import javax.annotation.Nonnull;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.regex.Pattern;
import static java.lang.String.format;
public class ScannerExample
{
private static final Set<String> EXIT_COMMANDS;
private static final Set<String> HELP_COMMANDS;
private static final Pattern DATE_PATTERN;
private static final String HELP_MESSAGE;
static
{
final SortedSet<String> ecmds = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
ecmds.addAll(Arrays.asList("exit", "done", "quit", "end", "fino"));
EXIT_COMMANDS = Collections.unmodifiableSortedSet(ecmds);
final SortedSet<String> hcmds = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
hcmds.addAll(Arrays.asList("help", "helpi", "?"));
HELP_COMMANDS = Collections.unmodifiableSet(hcmds);
DATE_PATTERN = Pattern.compile("\\d{4}([-\\/])\\d{2}\\1\\d{2}"); // http://regex101.com/r/xB8dR3/1
HELP_MESSAGE = format("Please enter some data or enter one of the following commands to exit %s", EXIT_COMMANDS);
}
/**
* Using exceptions to control execution flow is always bad.
* That is why this is encapsulated in a method, this is done this
* way specifically so as not to introduce any external libraries
* so that this is a completely self contained example.
* #param s possible url
* #return true if s represents a valid url, false otherwise
*/
private static boolean isValidURL(#Nonnull final String s)
{
try { new URL(s); return true; }
catch (final MalformedURLException e) { return false; }
}
private static void output(#Nonnull final String format, #Nonnull final Object... args)
{
System.out.println(format(format, args));
}
public static void main(final String[] args)
{
final Scanner sis = new Scanner(System.in);
output(HELP_MESSAGE);
while (sis.hasNext())
{
if (sis.hasNextInt())
{
final int next = sis.nextInt();
output("You entered an Integer = %d", next);
}
else if (sis.hasNextLong())
{
final long next = sis.nextLong();
output("You entered a Long = %d", next);
}
else if (sis.hasNextDouble())
{
final double next = sis.nextDouble();
output("You entered a Double = %f", next);
}
else if (sis.hasNext("\\d+"))
{
final BigInteger next = sis.nextBigInteger();
output("You entered a BigInteger = %s", next);
}
else if (sis.hasNextBoolean())
{
final boolean next = sis.nextBoolean();
output("You entered a Boolean representation = %s", next);
}
else if (sis.hasNext(DATE_PATTERN))
{
final String next = sis.next(DATE_PATTERN);
output("You entered a Date representation = %s", next);
}
else // unclassified
{
final String next = sis.next();
if (isValidURL(next))
{
output("You entered a valid URL = %s", next);
}
else
{
if (EXIT_COMMANDS.contains(next))
{
output("Exit command %s issued, exiting!", next);
break;
}
else if (HELP_COMMANDS.contains(next)) { output(HELP_MESSAGE); }
else { output("You entered an unclassified String = %s", next); }
}
}
}
/*
This will close the underlying InputStream, in this case System.in, and free those resources.
WARNING: You will not be able to read from System.in anymore after you call .close().
If you wanted to use System.in for something else, then don't close the Scanner.
*/
sis.close();
System.exit(0);
}
}
Notes:
This may look like a lot of code, but it illustrates the minimum
effort needed to use the Scanner class correctly and not have to
deal with subtle bugs and side effects that plague those new to
programming and this terribly implemented class called
java.util.Scanner. It tries to illustrate what idiomatic Java code
should look like and behave like.
Below are some of the things I was thinking about when I wrote this example:
JDK Version:
I purposely kept this example compatible with JDK 6. If some scenario really demands a feature of JDK 7/8 I or someone else will post a new answer with specifics about how to modify this for that version JDK.
The majority of questions about this class come from students and they usually have restrictions on what they can use to solve a problem so I restricted this as much as I could to show how to do the common things without any other dependencies. In the 22+ years I have been working with Java and consulting the majority of that time I have never encountered professional use of this class in the 10's of millions of lines source code I have seen.
Processing commands:
This shows exactly how to idiomatically read commands from the user interactively and dispatch those commands. The majority of questions about java.util.Scanner are of the how can I get my program to quit when I enter some specific input category. This shows that clearly.
Naive Dispatcher
The dispatch logic is intentionally naive so as to not complicate the solution for new readers. A dispatcher based on a Strategy Pattern or Chain Of Responsibility pattern would be more appropriate for real world problems that would be much more complex.
Error Handling
The code was deliberately structured as to require no Exception handling because there is no scenario where some data might not be correct.
.hasNext() and .hasNextXxx()
I rarely see anyone using the .hasNext() properly, by testing for the generic .hasNext() to control the event loop, and then using the if(.hasNextXxx()) idiom lets you decide how and what to proceed with your code without having to worry about asking for an int when none is available, thus no exception handling code.
.nextXXX() vs .nextLine()
This is something that breaks everyone's code. It is a finicky detail that should not have to be dealt with and has a very obfusated bug that is hard to reason about because of it breaks the Principal of Least Astonishment
The .nextXXX() methods do not consume the line ending. .nextLine() does.
That means that calling .nextLine() immediately after .nextXXX() will just return the line ending. You have to call it again to actually get the next line.
This is why many people advocate either use nothing but the .nextXXX() methods or only .nextLine() but not both at the same time so that this finicky behavior does not trip you up. Personally I think the type safe methods are much better than having to then test and parse and catch errors manually.
Immutablity:
Notice that there are no mutable variables used in the code, this is important to learn how to do, it eliminates four of the most major sources of runtime errors and subtle bugs.
No nulls means no possibility of a NullPointerExceptions!
No mutability means that you don't have to worry about method arguments changing or anything else changing. When you step debug through you never have to use watch to see what variables are change to what values, if they are changing. This makes the logic 100% deterministic when you read it.
No mutability means your code is automatically thread-safe.
No side effects. If nothing can change, the you don't have to worry about some subtle side effect of some edge case changing something unexpectedly!
Read this if you don't understand how to apply the final keyword in your own code.
Using a Set instead of massive switch or if/elseif blocks:
Notice how I use a Set<String> and use .contains() to classify the commands instead of a massive switch or if/elseif monstrosity that would bloat your code and more importantly make maintenance a nightmare! Adding a new overloaded command is as simple as adding a new String to the array in the constructor.
This also would work very well with i18n and i10n and the proper ResourceBundles.
A Map<Locale,Set<String>> would let you have multiple language support with very little overhead!
#Nonnull
I have decided that all my code should explicitly declare if something is #Nonnull or #Nullable. It lets your IDE help warn you about potential NullPointerException hazards and when you do not have to check.
Most importantly it documents the expectation for future readers that none of these method parameters should be null.
Calling .close()
Really think about this one before you do it.
What do you think will happen System.in if you were to call sis.close()? See the comments in the listing above.
Please fork and send pull requests and I will update this question and answer for other basic usage scenarios.
This is meant to be a canonical question/answer that can be used as a
duplicate target. These requirements are based on the most common
questions posted every day and may be added to as needed. They all
require the same basic code structure to get to each of the scenarios
and they are generally dependent on one another.
Scanner seems like a "simple" class to use, and that is where the first mistake is made. It is not simple, it has all kinds of non-obvious side effect and aberrant behaviors that break the Principle of Least Astonishment in very subtle ways.
So this might seem to be overkill for this class, but the peeling the onions errors and problems are all simple, but taken together they are very complex because of their interactions and side effects. This is why there are so many questions about it on Stack Overflow every day.
Common Scanner questions:
Most Scanner questions include failed attempts at more than one of these things.
I want to be able to have my program automatically wait for the next input after each previous input as well.
I want to know how to detect an exit command and end my program when that command is entered.
I want to know how to match multiple commands for the exit command in a case-insensitive way.
I want to be able to match regular expression patterns as well as the built-in primitives. For example, how to match what appears to be a date ( 2014/10/18 )?
I want to know how to match things that might not easily be implemented with regular expression matching - for example, an URL ( http://google.com ).
Motivation:
In the Java world, Scanner is a special case, it is an extremely finicky class that teachers should not give new students instructions to use. In most cases the instructors do not even know how to use it correctly. It is hardly if ever used in professional production code so its value to students is extremely questionable.
Using Scanner implies all the other things this question and answer mentions. It is never just about Scanner it is about how to solve these common problems with Scanner that are always co morbid problems in almost all the question that get Scanner wrong. It is never just about next() vs nextLine(), that is just a symptom of the finickiness of the implementation of the class, there are always other issues in the code posting in questions asking about Scanner.
The answer shows a complete, idiomatic implementation of 99% of cases where Scanner is used and asked about on StackOverflow.
Especially in beginner code. If you think this answer is too complex then complain to the instructors that tell new students to use Scanner before explaining the intricacies, quirks, non-obvious side effects and peculiarities of its behavior.
Scanner is the a great teaching moment about how important the Principle of least astonishment is and why consistent behavior and semantics are important in naming methods and method arguments.
Note to students:
You will probably never actually see Scanner used in
professional/commercial line of business apps because everything it
does is done better by something else. Real world software has to be
more resilient and maintainable than Scanner allows you to write
code. Real world software uses standardized file format parsers and
documented file formats, not the adhoc input formats that you are
given in stand alone assignments.
Idiomatic Example:
The following is how to properly use the java.util.Scanner class to interactively read user input from System.in correctly( sometimes referred to as stdin, especially in C, C++ and other languages as well as in Unix and Linux). It idiomatically demonstrates the most common things that are requested to be done.
package com.stackoverflow.scanner;
import javax.annotation.Nonnull;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.regex.Pattern;
import static java.lang.String.format;
public class ScannerExample
{
private static final Set<String> EXIT_COMMANDS;
private static final Set<String> HELP_COMMANDS;
private static final Pattern DATE_PATTERN;
private static final String HELP_MESSAGE;
static
{
final SortedSet<String> ecmds = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
ecmds.addAll(Arrays.asList("exit", "done", "quit", "end", "fino"));
EXIT_COMMANDS = Collections.unmodifiableSortedSet(ecmds);
final SortedSet<String> hcmds = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
hcmds.addAll(Arrays.asList("help", "helpi", "?"));
HELP_COMMANDS = Collections.unmodifiableSet(hcmds);
DATE_PATTERN = Pattern.compile("\\d{4}([-\\/])\\d{2}\\1\\d{2}"); // http://regex101.com/r/xB8dR3/1
HELP_MESSAGE = format("Please enter some data or enter one of the following commands to exit %s", EXIT_COMMANDS);
}
/**
* Using exceptions to control execution flow is always bad.
* That is why this is encapsulated in a method, this is done this
* way specifically so as not to introduce any external libraries
* so that this is a completely self contained example.
* #param s possible url
* #return true if s represents a valid url, false otherwise
*/
private static boolean isValidURL(#Nonnull final String s)
{
try { new URL(s); return true; }
catch (final MalformedURLException e) { return false; }
}
private static void output(#Nonnull final String format, #Nonnull final Object... args)
{
System.out.println(format(format, args));
}
public static void main(final String[] args)
{
final Scanner sis = new Scanner(System.in);
output(HELP_MESSAGE);
while (sis.hasNext())
{
if (sis.hasNextInt())
{
final int next = sis.nextInt();
output("You entered an Integer = %d", next);
}
else if (sis.hasNextLong())
{
final long next = sis.nextLong();
output("You entered a Long = %d", next);
}
else if (sis.hasNextDouble())
{
final double next = sis.nextDouble();
output("You entered a Double = %f", next);
}
else if (sis.hasNext("\\d+"))
{
final BigInteger next = sis.nextBigInteger();
output("You entered a BigInteger = %s", next);
}
else if (sis.hasNextBoolean())
{
final boolean next = sis.nextBoolean();
output("You entered a Boolean representation = %s", next);
}
else if (sis.hasNext(DATE_PATTERN))
{
final String next = sis.next(DATE_PATTERN);
output("You entered a Date representation = %s", next);
}
else // unclassified
{
final String next = sis.next();
if (isValidURL(next))
{
output("You entered a valid URL = %s", next);
}
else
{
if (EXIT_COMMANDS.contains(next))
{
output("Exit command %s issued, exiting!", next);
break;
}
else if (HELP_COMMANDS.contains(next)) { output(HELP_MESSAGE); }
else { output("You entered an unclassified String = %s", next); }
}
}
}
/*
This will close the underlying InputStream, in this case System.in, and free those resources.
WARNING: You will not be able to read from System.in anymore after you call .close().
If you wanted to use System.in for something else, then don't close the Scanner.
*/
sis.close();
System.exit(0);
}
}
Notes:
This may look like a lot of code, but it illustrates the minimum
effort needed to use the Scanner class correctly and not have to
deal with subtle bugs and side effects that plague those new to
programming and this terribly implemented class called
java.util.Scanner. It tries to illustrate what idiomatic Java code
should look like and behave like.
Below are some of the things I was thinking about when I wrote this example:
JDK Version:
I purposely kept this example compatible with JDK 6. If some scenario really demands a feature of JDK 7/8 I or someone else will post a new answer with specifics about how to modify this for that version JDK.
The majority of questions about this class come from students and they usually have restrictions on what they can use to solve a problem so I restricted this as much as I could to show how to do the common things without any other dependencies. In the 22+ years I have been working with Java and consulting the majority of that time I have never encountered professional use of this class in the 10's of millions of lines source code I have seen.
Processing commands:
This shows exactly how to idiomatically read commands from the user interactively and dispatch those commands. The majority of questions about java.util.Scanner are of the how can I get my program to quit when I enter some specific input category. This shows that clearly.
Naive Dispatcher
The dispatch logic is intentionally naive so as to not complicate the solution for new readers. A dispatcher based on a Strategy Pattern or Chain Of Responsibility pattern would be more appropriate for real world problems that would be much more complex.
Error Handling
The code was deliberately structured as to require no Exception handling because there is no scenario where some data might not be correct.
.hasNext() and .hasNextXxx()
I rarely see anyone using the .hasNext() properly, by testing for the generic .hasNext() to control the event loop, and then using the if(.hasNextXxx()) idiom lets you decide how and what to proceed with your code without having to worry about asking for an int when none is available, thus no exception handling code.
.nextXXX() vs .nextLine()
This is something that breaks everyone's code. It is a finicky detail that should not have to be dealt with and has a very obfusated bug that is hard to reason about because of it breaks the Principal of Least Astonishment
The .nextXXX() methods do not consume the line ending. .nextLine() does.
That means that calling .nextLine() immediately after .nextXXX() will just return the line ending. You have to call it again to actually get the next line.
This is why many people advocate either use nothing but the .nextXXX() methods or only .nextLine() but not both at the same time so that this finicky behavior does not trip you up. Personally I think the type safe methods are much better than having to then test and parse and catch errors manually.
Immutablity:
Notice that there are no mutable variables used in the code, this is important to learn how to do, it eliminates four of the most major sources of runtime errors and subtle bugs.
No nulls means no possibility of a NullPointerExceptions!
No mutability means that you don't have to worry about method arguments changing or anything else changing. When you step debug through you never have to use watch to see what variables are change to what values, if they are changing. This makes the logic 100% deterministic when you read it.
No mutability means your code is automatically thread-safe.
No side effects. If nothing can change, the you don't have to worry about some subtle side effect of some edge case changing something unexpectedly!
Read this if you don't understand how to apply the final keyword in your own code.
Using a Set instead of massive switch or if/elseif blocks:
Notice how I use a Set<String> and use .contains() to classify the commands instead of a massive switch or if/elseif monstrosity that would bloat your code and more importantly make maintenance a nightmare! Adding a new overloaded command is as simple as adding a new String to the array in the constructor.
This also would work very well with i18n and i10n and the proper ResourceBundles.
A Map<Locale,Set<String>> would let you have multiple language support with very little overhead!
#Nonnull
I have decided that all my code should explicitly declare if something is #Nonnull or #Nullable. It lets your IDE help warn you about potential NullPointerException hazards and when you do not have to check.
Most importantly it documents the expectation for future readers that none of these method parameters should be null.
Calling .close()
Really think about this one before you do it.
What do you think will happen System.in if you were to call sis.close()? See the comments in the listing above.
Please fork and send pull requests and I will update this question and answer for other basic usage scenarios.
I'm coding a lexical analyzer in java and need to look backwards or forwards easily in a list of custom datatypes (my tokens). I've tried saving the next and previous item as a copy, but then I figured out that I need to look arbitrarily far ahead or back. I then tried to use an index, but it was beyond unpleasant to debug that since I had to think about decreasing, increasing and getting the current position in a pinch (I even had the objects store an int of where they were at) all the while keeping within range of the list, so it was an ugly, hard to read mess of spaghetti code too at that.
I then looked into linked lists, but they don't quite work like I want them too. I want a node and I want to be able to look ahead for two or three positions, or back, and I didn't really find any good tools for that at that place.
Right now, I'm trying out iterators but I have the same problem as with indexes: I have to decrease and increase back again to where I was at since next() moves the cursor instead of just "peeking ahead".
I'm thinking of coding my own linked list and just hitting node.next().next() if I want to go two steps forward, or a loop repeatedly hitting it if I want to go longer than that. Is there any built in way in Java saving me from this?
You're getting spaghetti code because you're not following SoC. One way to help yourself is to create a specialized collection class that implements functions which, for your problem domain, hide the ugly particulars of array navigation such as tracking the current position, iterating N steps back and forth, "peeking" back and forth, etc.
There are a hundred ways to do this but in my code sample below I chose to compose with rather than extend the ArrayList<> class. I chose ArrayList<> because of its random access capabilities and chose not to extend to help stay away from manipulating the ArrayList<> directly from client code and getting back into a spaghetti mess. I wasn't considering performance but as it happens that ArrayList<>'s random access functions are mostly O(1) rather than O(n) which you would get if you used an iterator or linked list. With those collection types you would also be forced to traverse through the collection just to peek at an object which hurts performance further and also makes implementation that much harder.
Here is a link to an Ideone implementation of my suggested solution. It is a bit different from the code shown below due to the complexities imposed by an online Java compiler but the code is easily accessible and fully executable.
Code sample notes: This is a full, working sample which contain three classes necessary to demostrate the concepts. There is a class to hold the main function which demonstrates usage of the collection class and also acts as a poor-man's unit test. There is a POJO-style class to represent a node or token and finally the utility class which exposes a specialized set of functions, or API. The code is very basic and naive. There is no error or bounds checking of any kind but it demonstrates my suggestion fairly well, IMHO.
To the code! Here is the main function which initializes the NodeList with an arbitrary, Java-like line of code and then proceeds to peek and move in the token list. Note that there is no variable needed in the client code to track what's going on. The navigation is all handled within the NodeList class. The client code's concerns now do not include that ugliness.
import java.util.*;
import java.io.*;
public class TestNodeList {
public static void main(String[] args) {
// usage: basic initialization
NodeList nl = new NodeList();
nl.add(new Node("someUtilObj"));
nl.add(new Node("."));
nl.add(new Node("print"));
nl.add(new Node("("));
nl.add(new Node("myIntValue"));
nl.add(new Node(")"));
nl.add(new Node(";"));
nl.print();
// usage: using the API, moving and peeking
nl.peekAhead(1).print();
nl.peekAhead(2).print();
nl.peekAhead(3).print();
nl.moveAhead(2).print();
nl.getCurrentNode().print();
nl.peekBack(2).print();
}
}
This is the implementation of the specialized collection with some fields and functions I assume would be useful for your lexical analysis. Again, it is quite bare but covers the more important concepts.
public class NodeList {
private ArrayList<Node> nodeList = new ArrayList<Node>();
private int currentNodeIndex = 0;
public void add(Node node) {
nodeList.add(node);
}
// Node is private/read-only - currentNode should only be set by internal operations
public Node getCurrentNode() {
return nodeList.get(currentNodeIndex);
}
// moving back and forth
public Node moveAhead(int count) {
currentNodeIndex += count;
return nodeList.get(currentNodeIndex);
}
public Node moveBack(int count) {
currentNodeIndex -= count;
return nodeList.get(currentNodeIndex);
}
// peeking back and forth
public Node peekAhead(int count) {
return nodeList.get(currentNodeIndex + count);
}
public Node peekBack(int count) {
return nodeList.get(currentNodeIndex - count);
}
public void print() {
for (int i=0; i<nodeList.size(); i++) {
System.out.print(nodeList.get(i).getToken());
}
System.out.println("");
}
}
Other functions to consider implementing for a better, cleaner API:
peekNext() - same as peekAhead(1) but w/o the magic number. I would think that this would also be the most frequently called function in your specialized collection so it makes sense to have a shorter, cleaner version of the operation than peekAhead(1)
peekPrev() - same as peekBack(1) but w/o the magic number
moveNext() - same as moveAhead(1) but w/o the magic number. This would also be a frequently called function in your API and a cleaner version of moveAhead(1)
movePrev() - same as moveBack(1) but w/o the magic number
peekAt(int) - Peek at an element at a specific index in the collection
jumpTo(int) - Move current position to an element at a specific index in the collection
moveFirst() - Resets your current position to the 0th element in the collection
Here are a few more but I'm not sure they would be very useful:
moveLast() - Sets current position to the last element in the collection
peekFirst() - Peek at the 0th element in the collection
peekLast() - Peek at the last element in the collection
To properly implement the functions listed above you should stay consistent and treat them almost like overloads. So, for example, internally peekNext() would actually just call peekAhead(1). This would keep your API's behavior consistent and simpler to maintain in case the implementation of the core function, peekAhead, needs to change.
And finally, here's the POJO. It just contains a single field, the token value, and a function to help write the value to console. Notice that the class does not have an index to itself because it isn't necessary.
// Your node/token class
public class Node {
private String token;
public Node(String token) {
this.token = token;
}
public String getToken() {
return token;
}
public void print() {
System.out.println(token);
}
}
For traversing forward and backwards you can use ListIterator instead of Iterator. You can get it from the LinkedList:
http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html#listIterator(int)
This is meant to be a canonical question/answer that can be used as a
duplicate target. These requirements are based on the most common
questions posted every day and may be added to as needed. They all
require the same basic code structure to get to each of the scenarios
and they are generally dependent on one another.
Scanner seems like a "simple" class to use, and that is where the first mistake is made. It is not simple, it has all kinds of non-obvious side effect and aberrant behaviors that break the Principle of Least Astonishment in very subtle ways.
So this might seem to be overkill for this class, but the peeling the onions errors and problems are all simple, but taken together they are very complex because of their interactions and side effects. This is why there are so many questions about it on Stack Overflow every day.
Common Scanner questions:
Most Scanner questions include failed attempts at more than one of these things.
I want to be able to have my program automatically wait for the next input after each previous input as well.
I want to know how to detect an exit command and end my program when that command is entered.
I want to know how to match multiple commands for the exit command in a case-insensitive way.
I want to be able to match regular expression patterns as well as the built-in primitives. For example, how to match what appears to be a date ( 2014/10/18 )?
I want to know how to match things that might not easily be implemented with regular expression matching - for example, an URL ( http://google.com ).
Motivation:
In the Java world, Scanner is a special case, it is an extremely finicky class that teachers should not give new students instructions to use. In most cases the instructors do not even know how to use it correctly. It is hardly if ever used in professional production code so its value to students is extremely questionable.
Using Scanner implies all the other things this question and answer mentions. It is never just about Scanner it is about how to solve these common problems with Scanner that are always co morbid problems in almost all the question that get Scanner wrong. It is never just about next() vs nextLine(), that is just a symptom of the finickiness of the implementation of the class, there are always other issues in the code posting in questions asking about Scanner.
The answer shows a complete, idiomatic implementation of 99% of cases where Scanner is used and asked about on StackOverflow.
Especially in beginner code. If you think this answer is too complex then complain to the instructors that tell new students to use Scanner before explaining the intricacies, quirks, non-obvious side effects and peculiarities of its behavior.
Scanner is the a great teaching moment about how important the Principle of least astonishment is and why consistent behavior and semantics are important in naming methods and method arguments.
Note to students:
You will probably never actually see Scanner used in
professional/commercial line of business apps because everything it
does is done better by something else. Real world software has to be
more resilient and maintainable than Scanner allows you to write
code. Real world software uses standardized file format parsers and
documented file formats, not the adhoc input formats that you are
given in stand alone assignments.
Idiomatic Example:
The following is how to properly use the java.util.Scanner class to interactively read user input from System.in correctly( sometimes referred to as stdin, especially in C, C++ and other languages as well as in Unix and Linux). It idiomatically demonstrates the most common things that are requested to be done.
package com.stackoverflow.scanner;
import javax.annotation.Nonnull;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.regex.Pattern;
import static java.lang.String.format;
public class ScannerExample
{
private static final Set<String> EXIT_COMMANDS;
private static final Set<String> HELP_COMMANDS;
private static final Pattern DATE_PATTERN;
private static final String HELP_MESSAGE;
static
{
final SortedSet<String> ecmds = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
ecmds.addAll(Arrays.asList("exit", "done", "quit", "end", "fino"));
EXIT_COMMANDS = Collections.unmodifiableSortedSet(ecmds);
final SortedSet<String> hcmds = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
hcmds.addAll(Arrays.asList("help", "helpi", "?"));
HELP_COMMANDS = Collections.unmodifiableSet(hcmds);
DATE_PATTERN = Pattern.compile("\\d{4}([-\\/])\\d{2}\\1\\d{2}"); // http://regex101.com/r/xB8dR3/1
HELP_MESSAGE = format("Please enter some data or enter one of the following commands to exit %s", EXIT_COMMANDS);
}
/**
* Using exceptions to control execution flow is always bad.
* That is why this is encapsulated in a method, this is done this
* way specifically so as not to introduce any external libraries
* so that this is a completely self contained example.
* #param s possible url
* #return true if s represents a valid url, false otherwise
*/
private static boolean isValidURL(#Nonnull final String s)
{
try { new URL(s); return true; }
catch (final MalformedURLException e) { return false; }
}
private static void output(#Nonnull final String format, #Nonnull final Object... args)
{
System.out.println(format(format, args));
}
public static void main(final String[] args)
{
final Scanner sis = new Scanner(System.in);
output(HELP_MESSAGE);
while (sis.hasNext())
{
if (sis.hasNextInt())
{
final int next = sis.nextInt();
output("You entered an Integer = %d", next);
}
else if (sis.hasNextLong())
{
final long next = sis.nextLong();
output("You entered a Long = %d", next);
}
else if (sis.hasNextDouble())
{
final double next = sis.nextDouble();
output("You entered a Double = %f", next);
}
else if (sis.hasNext("\\d+"))
{
final BigInteger next = sis.nextBigInteger();
output("You entered a BigInteger = %s", next);
}
else if (sis.hasNextBoolean())
{
final boolean next = sis.nextBoolean();
output("You entered a Boolean representation = %s", next);
}
else if (sis.hasNext(DATE_PATTERN))
{
final String next = sis.next(DATE_PATTERN);
output("You entered a Date representation = %s", next);
}
else // unclassified
{
final String next = sis.next();
if (isValidURL(next))
{
output("You entered a valid URL = %s", next);
}
else
{
if (EXIT_COMMANDS.contains(next))
{
output("Exit command %s issued, exiting!", next);
break;
}
else if (HELP_COMMANDS.contains(next)) { output(HELP_MESSAGE); }
else { output("You entered an unclassified String = %s", next); }
}
}
}
/*
This will close the underlying InputStream, in this case System.in, and free those resources.
WARNING: You will not be able to read from System.in anymore after you call .close().
If you wanted to use System.in for something else, then don't close the Scanner.
*/
sis.close();
System.exit(0);
}
}
Notes:
This may look like a lot of code, but it illustrates the minimum
effort needed to use the Scanner class correctly and not have to
deal with subtle bugs and side effects that plague those new to
programming and this terribly implemented class called
java.util.Scanner. It tries to illustrate what idiomatic Java code
should look like and behave like.
Below are some of the things I was thinking about when I wrote this example:
JDK Version:
I purposely kept this example compatible with JDK 6. If some scenario really demands a feature of JDK 7/8 I or someone else will post a new answer with specifics about how to modify this for that version JDK.
The majority of questions about this class come from students and they usually have restrictions on what they can use to solve a problem so I restricted this as much as I could to show how to do the common things without any other dependencies. In the 22+ years I have been working with Java and consulting the majority of that time I have never encountered professional use of this class in the 10's of millions of lines source code I have seen.
Processing commands:
This shows exactly how to idiomatically read commands from the user interactively and dispatch those commands. The majority of questions about java.util.Scanner are of the how can I get my program to quit when I enter some specific input category. This shows that clearly.
Naive Dispatcher
The dispatch logic is intentionally naive so as to not complicate the solution for new readers. A dispatcher based on a Strategy Pattern or Chain Of Responsibility pattern would be more appropriate for real world problems that would be much more complex.
Error Handling
The code was deliberately structured as to require no Exception handling because there is no scenario where some data might not be correct.
.hasNext() and .hasNextXxx()
I rarely see anyone using the .hasNext() properly, by testing for the generic .hasNext() to control the event loop, and then using the if(.hasNextXxx()) idiom lets you decide how and what to proceed with your code without having to worry about asking for an int when none is available, thus no exception handling code.
.nextXXX() vs .nextLine()
This is something that breaks everyone's code. It is a finicky detail that should not have to be dealt with and has a very obfusated bug that is hard to reason about because of it breaks the Principal of Least Astonishment
The .nextXXX() methods do not consume the line ending. .nextLine() does.
That means that calling .nextLine() immediately after .nextXXX() will just return the line ending. You have to call it again to actually get the next line.
This is why many people advocate either use nothing but the .nextXXX() methods or only .nextLine() but not both at the same time so that this finicky behavior does not trip you up. Personally I think the type safe methods are much better than having to then test and parse and catch errors manually.
Immutablity:
Notice that there are no mutable variables used in the code, this is important to learn how to do, it eliminates four of the most major sources of runtime errors and subtle bugs.
No nulls means no possibility of a NullPointerExceptions!
No mutability means that you don't have to worry about method arguments changing or anything else changing. When you step debug through you never have to use watch to see what variables are change to what values, if they are changing. This makes the logic 100% deterministic when you read it.
No mutability means your code is automatically thread-safe.
No side effects. If nothing can change, the you don't have to worry about some subtle side effect of some edge case changing something unexpectedly!
Read this if you don't understand how to apply the final keyword in your own code.
Using a Set instead of massive switch or if/elseif blocks:
Notice how I use a Set<String> and use .contains() to classify the commands instead of a massive switch or if/elseif monstrosity that would bloat your code and more importantly make maintenance a nightmare! Adding a new overloaded command is as simple as adding a new String to the array in the constructor.
This also would work very well with i18n and i10n and the proper ResourceBundles.
A Map<Locale,Set<String>> would let you have multiple language support with very little overhead!
#Nonnull
I have decided that all my code should explicitly declare if something is #Nonnull or #Nullable. It lets your IDE help warn you about potential NullPointerException hazards and when you do not have to check.
Most importantly it documents the expectation for future readers that none of these method parameters should be null.
Calling .close()
Really think about this one before you do it.
What do you think will happen System.in if you were to call sis.close()? See the comments in the listing above.
Please fork and send pull requests and I will update this question and answer for other basic usage scenarios.