How do I get Java hasNextInt () to stop waiting for ints without entering a character?
I was presented with the following code and asked to write a Solution class extending from TestList. I wrote a constructor for it (called super) and a printSecond2 () method that is called in the last line of code below. All other methods are inherited. Here's the code:
public class Test3A {
public static void main(String[] args) {
TestList tl = new Solution();
tl.loadList();
((Solution) (tl)).printSecond2();//prints every second element
}
}
However, heck, nothing was printed, so I went to the TestList class (which was provided) and put println statements after each line of the loadList () method:
public void loadList ()
{
if (input.hasNextInt ())//input is a Scanner object
{
int number = input.nextInt ();
loadList ();
add (number);
}
}
I found that I can keep adding spaces, newlines, and integers indefinitely and that the add (number) method is only finally called when a character is entered. So if I don't, it just hangs, waiting for more input instead of moving on.
I am confused by this as the provided I / O sample:
sample entry
1 2 3 4 5
sample withdrawal
2 4
Thus, no character is entered with an automatic marker.
I tried to override the method in the solution (we cannot touch on other classes) and:
- ), if for a while
- ) adding the else block
- ) adding else if (! input.hasNextInt ())
None of this has changed. I have no idea how the program should move on and get to the call printSecond2()
.
Any thoughts? I would really like to pass my next prac exam: D
source to share
When the user must enter a sequence of numbers, the cardinality must be specified or the input must be interrupted in some way. 1 2 3 and 1 2 3 4 are valid inputs, so the scanner cannot decide where to end on its own. It can be assumed that the number sequence ends with EOF Ctrl-Z on windows and Ctrl-D on unix, since no other information is provided.
source to share
There is a way to stop Scanner
at the end of the line. You need to define a separator containing spaces, an empty expression, but not the following line character:
public static void main(final String[] args) {
Scanner scan = new Scanner(System.in).useDelimiter(" *");
while (scan.hasNextInt() && scan.hasNext()) {
int x = scan.nextInt();
System.out.println(x);
}
}
So Scanner
sees \n
followed by a delimiter (nothing) and entry stops after hitting return.
source to share