我刚刚浏览了70个关于java的视频系列。是时候脱掉训练轮所以我正在制作一个非常简单的程序来为一个班级提供2个文本输入。它首先制作Car
,但在第二个时抛出错误。我无法弄清楚原因。
import java.util.Scanner;
class Car{
public int cost;
public double mpg;
public void enterInfo() {
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter cost: ");
this.cost = reader.nextInt(); // Scans the next token of the input as an int.
System.out.println("Enter MPG: ");
this.mpg = reader.nextDouble();
reader.close();
}
}
public class App {
public static void main(String[] args) {
Car car1 = new Car();
car1.enterInfo();
Car car2 = new Car();
car2.enterInfo();
System.out.println(car1.cost);
}
}
这是错误
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at uda01.Car.enterInfo(App.java:13)
at uda01.App.main(App.java:32)
答案 0 :(得分:1)
问题是您在从中读取第一个Car
对象后关闭扫描仪。当您这样做时,Scanner
closes its underlying stream,即System.in
:
如果此扫描程序尚未关闭,那么如果其底层可读也实现了
Closeable
接口,则将调用可读的close方法。
这就是为什么第二次阅读不成功。
解决此问题的一种方法是在Scanner
中制作main
,将其传递给enterInfo
,并在main
结束后关闭:
public static void main(String[] args) {
Car car1 = new Car();
Car car2 = new Car();
// Try with resource automatically closes your Scanner
try(Scanner scanner = new Scanner(System.in)){
car1.enterInfo(scanner);
car2.enterInfo(scanner);
}
System.out.println(car1.cost);
System.out.println(car2.cost);
}
答案 1 :(得分:1)
我只是想用dasblinkenlight说同样的话。每次调用此方法时都不应创建扫描程序。更合适的方式是发送Scanner as a param
。
所以,你可以更新你的代码:
public class Car {
public int cost;
public double mpg;
public void enterInfo(Scanner reader) {
System.out.println("Enter cost: ");
this.cost = reader.nextInt(); // Scans the next token of the input as an int.
System.out.println("Enter MPG: ");
this.mpg = reader.nextDouble();
}
}
public class App {
public static void main(String[] args) {
try (Scanner reader = new Scanner(System.in)) {
Car car1 = new Car();
car1.enterInfo(reader);
Car car2 = new Car();
car2.enterInfo(reader);
System.out.println(car1.cost);
}
}
}