开发者

How do I get Java's hasNextInt() to stop waiting for ints without inputting a character?

I was given the开发者_开发知识库 following code and asked to write the Solution class extending from TestList. I wrote a constructor for it (which just called super) and the printSecond2() method invoked in the last line of the 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, the damn thing was never printing anything out, so I went into the TestList class (which was provided) and put println statements after every single line of the loadList () method:

   public void loadList ()
   {
      if (input.hasNextInt ())//input is a Scanner object
      {
         int number = input.nextInt ();
         loadList ();
         add (number);
      }
   }

I discovered that I can continue to add whitespace, newlines and integers indefinitely, and that the add(number) method is only finally called when I input a character. So if I don't do that, it just sort of hangs around waiting for more input instead of moving on.

I'm confused by this as the provided sample input/output is:

sample input

1 2 3 4 5

sample output

2 4

So there's no character being inputted by the automatic marker.

I have tried overriding the method in Solution (we can't touch the other classes) and:

  1. ) changing if to while
  2. ) adding an else block
  3. ) adding an else if (!input.hasNextInt ())

None of these changed anything. I have no idea how the program is supposed to move on and get as far as calling printSecond2().

Any thoughts? I'd really like to pass my next prac test :D


When user is supposed to enter a sequence of numbers either the number of items should be provided or the input should be terminated in some manner. 1 2 3 and 1 2 3 4 are both valid inputs so scanner can't decide where to end on its own. It can be assumed that the number sequence is terminated by EOF character Ctrl-Z on windows and Ctrl-D on unix as no other information is given.


There is a way to stop the Scanner at the end of the line. You need to define a delimiter that contains whitespace, the empty expression, but not the next 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);
    }

}

This way the Scanner sees the \n followed by a delimiter (nothing) and the input stops after pressing return.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜