我有一个创建多个 Integer
对象并将它们放入 LinkedList
的类,如下所示:
public class Shares<E> implements Queue<E> {
protected LinkedList<E> L;
public Shares() {
L = new LinkedList<E>();
}
public boolean add(E price) {
System.out.println("How many of these shares would you like?");
Scanner scanInt;
scanInt = new Scanner(System.in);
Integer noShares = scanInt.nextInt();
for (int i = 0; i < noShares; i++) {
L.addLast(price);
}
scanInt.close();
return true;
}
}
我有一个应用程序从控制台扫描输入“add”,如果找到,调用方法 add
,如下所示:
public class Application {
private static Scanner scan;
public static <E> void main(String[] args) {
Queue<Integer> S = new Shares<Integer>();
scan = new Scanner(System.in);
System.out.println("Please type add");
String sentence = scan.nextLine();
while (sentence.equals("quit") == false) {
if (sentence.equals("add")) {
System.out
.println("What price would you like to buy your shares at?");
S.add((Integer) scan.nextInt());
} else
System.exit(0);
sentence = scan.nextLine();
}
}
}
应用程序应允许用户根据需要多次输入“add”,但在调用 add
方法后出现“找不到行”错误。
我猜这是因为方法中的 Scanner
没有关闭,然后在需要时重新打开。这是程序的问题所在吗?如果是,我该如何解决?
请注意,这个程序还没有完成,因为我将添加一个出售这些股票的出售方法。这就是我使用 while 循环的原因。
最佳答案
为任何流使用多个包装器是真正让自己感到困惑的好方法。我建议您只包装一次流,除非您真的知道自己在做什么。
最简单的方法是在这种情况下使用单例,因为它包装了另一个单例(最好是将 Scanner 作为参数传递)
public class Application {
// use this Scanner in all you other code, don't create another one.
static final Scanner scan = new Scanner(System.in);
public static <E> void main(String[] args) {
Im guessing this is because the scanner in the method has not been closed
一旦您关闭流,它就会关闭底层流并且您不能再次使用它。如果您想防止再次使用它,请仅关闭 System.in。
how would I go about fixing it?
最好的解决方案是让所有扫描仪在一个地方、一种方法或一个类中使用。您让 main() 完成与用户的所有交互并将值传递给您的数据结构。让对象自行初始化是一种不好的做法,如果你开始这样做,它将在你余下的开发日子里困扰你;)(说真的,你会一次又一次地看到这样做,这通常是一场噩梦)
顺便说一句,永远不要在没有解释的情况下退出程序。在没有错误消息的情况下调用 System.exit(0);
也是一场噩梦。我曾经参与过一个项目,该项目对 System.exit() 进行了 260 次调用,但通常没有出现错误消息,您可以想象诊断服务器无故停止是多么有趣。
关于Java 多重扫描器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19766566/