如何在System.in上使用多个Scanner对象? [英] How to use multiple Scanner objects on System.in?

查看:308
本文介绍了如何在System.in上使用多个Scanner对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中使用多个Scanner对象的正确方法是什么。例如,我使用扫描仪来读取文件,然后根据文件中的内容,我再次使用扫描仪来提示用户输入。我的代码的摘录显示

what's the correct way to use multiple Scanner objects in my program. For example, I use scanner to read a file, then depending on what is found in the file, i use scanner again to prompt for user input. An extract of my code is shown

....
Scanner f = new Scanner (System.in); //get the file name
String fileName = f.next();
Scanner input = new Scanner( new File( fileName ) );
while ( input.hasNext() )
{
   String currentLine = input.nextLine();
   if ( some pattern found) {
       Scanner getUserInput = new Scanner (System.in);
       String userInput = getUserInput.next();
       .....
   }
}
....

它似乎不起作用。我需要使用 userInput.close()吗?我究竟做错了什么。 ?

It doesn't seem to work. Do I need to use userInput.close() ? What am i doing wrong. ?

我不明白的是,第一个 System.in 只是获取文件名。之后,为什么它会干扰第二个 System.in
至于输入对象,它从文件读取而不是从 System.in 读取。

What I don't understand is, the first System.in is just getting the file name. After that, why does it interfere with the second System.in. As for the input object, its reading from a File and not from System.in.

推荐答案


我做错了什么?

What am I doing wrong?

在同一个流上使用多个扫描程序是潜在的问题。扫描仪可以(并且将会)消耗流 - 这可能(将)导致意外的副作用。最好不要这样做。

Using multiple scanners on the same stream is the underlying problem. Scanners can (and will) consume the stream - this may (will) lead to unexpected side-effects. Best not to do it.

如果输入已关闭,则输入​​(但字符串没有关闭方法)对所有人来说都是封闭的 - 这对任何人来说都不是很有趣。

If the input is closed, then the input (but Strings have no close method) is closed for everyone - and that's not much fun for anyone.

编辑详情了解多个扫描仪坏的原因:不要在InputStream上创建多个缓冲的包装器

"Details" on why multiple scanners are bad: Do not create multiple buffered wrappers on an InputStream


...任何缓冲的包装器是不安全的;如果使用扫描仪,这种情况也可以利用......

...any buffered wrapper is unsafe; this condition is also exploitable if a Scanner is used instead...

另见 Java代码问题...扫描程序相关?还讨论了一些方法。

See also Java code question ... scanner related? which also talks about some approaches.

这篇关于如何在System.in上使用多个Scanner对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆