Java遇到这个问题该怎么解决:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at jsjsjs.Main.main(Main.java:23)
```代码是这样的
```java
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Zoo zoo = new Zoo();
while (true) {
System.out.println("1) Add a hedgehog, 2) Let them speak, 3) List animals, 0) Exit");
int option = scanner.nextInt();
scanner.nextLine();
if (option == 0) {
break;
}
if (option == 1) {
System.out.print("Give a name to the hedgehog: ");
String name = scanner.nextLine();
Hedgehog h = new Hedgehog(name);
zoo.addAnimal(h);
System.out.println("Hi, my name is " + name + ".");
}
if (option == 2) {
System.out.print("What should hedgehogs say? ");
String message = scanner.nextLine();
zoo.letThemSpeak(message);
}
if (option == 3) {
zoo.listAnimals();
}
}
scanner.close();
}
}
class Hedgehog {
String name;
public Hedgehog(String name) {
this.name = name;
}
public void speak(String message) {
System.out.println(this.name + ": " + message);
}
}
class Zoo {
private ArrayList hedgehogs;
public Zoo() {
this.hedgehogs = new ArrayList();
}
public void addAnimal(Hedgehog h) {
this.hedgehogs.add(h);
}
public void letThemSpeak(String message) {
for (Hedgehog h : hedgehogs) {
if (!message.matches("\\d+")) {
h.speak(message);
} else {
h.speak("I am a hedgehog. I do not understand numbers.");
}
}
}
public void listAnimals() {
for (Hedgehog h : hedgehogs) {
System.out.println(h.name);
}
}
}
Scanner 执行完的时候关闭一下
scanner.close();
望采纳。。。
你可以用如下这样:
while(sc.hasNextLine()){
str = sc.nextLine();
}
将 scanner.close(); 删掉
option = sc.nextInt();换成这个了
最后怎么改的啊 我也遇到这个问题