如何获取Java的hasNextInt()来停止等待int而不输入字符? [英] How do I get Java's hasNextInt() to stop waiting for ints without inputting a character?
问题描述
为我提供了以下代码,并要求编写从TestList扩展的Solution类.我为此编写了一个构造函数(仅称为super),并在下面代码的最后一行中调用了printSecond2()方法.所有其他方法都是继承的.这是代码:
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
}
}
但是,该死的东西从不打印任何东西,所以我进入了TestList类(已提供),并将println语句放在loadList()方法的每一行之后:
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);
}
}
我发现我可以继续无限期地添加空格,换行符和整数,并且只有在输入字符时才最终调用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:
样本输入
1 2 3 4 5
样本输出
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:
- )更改为while
- )添加else块
- )添加else if(!input.hasNextInt())
这些都没有改变任何东西.我不知道程序应该如何继续运行并达到调用printSecond2()
的程度.
None of these changed anything. I have no idea how the program is supposed to move on and get as far as calling printSecond2()
.
有什么想法吗?我真的很想通过我的下一个实践测试:D
Any thoughts? I'd really like to pass my next prac test :D
推荐答案
当用户应输入数字序列时,应提供项目数或以某种方式终止输入. 1 2 3和1 2 3 4都是有效输入,因此扫描仪无法自行决定在何处结束. 可以假定,由于没有给出其他信息,所以数字序列在Windows上以EOF字符Ctrl-Z终止,在Unix上以Ctrl-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.
这篇关于如何获取Java的hasNextInt()来停止等待int而不输入字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!