我正在为我的学习做作业,但每次执行我的程序时都会出错。错误是“线程中的异常”主“java.util.NoSuchElementException”。
我不知道如何解决这个问题,任何人都可以帮助我吗?
这是我的计划:
import java.util.Scanner;
class Cellulitis {
Scanner sc = new Scanner(System.in);
static char automata;//type A or B automaton
static int length; //length of row
static int gen; //generation
static boolean[] cellrow;
static boolean[] newCellrow;
void readGeneral() {//define different variables
automata = sc.next().charAt(0);
length = sc.nextInt() + 2;
gen = sc.nextInt();
cellrow = new boolean[length];
newCellrow = new boolean[length];
}
void readInitialConfiguration() {//input initial configuration
sc.next();
while (sc.hasNextInt()) {
cellrow[sc.nextInt()] = true;
}
}
void draw() {//prints out each cellrow
for(int i = 0; i < length-1; i++) {
if(cellrow[i]){
System.out.print('*');
}
else{
System.out.print(' ');
}
}
System.out.println("");
}
boolean newCellValueByA(int k){//calculates the state of each cell by the last cellrow by rules of automaton A
if (cellrow[k]) {
if((!cellrow[k-1] && cellrow[k+1]) || (cellrow[k-1] && !cellrow[k+1])){
return true;
}
else{
return false;
}
}
else{
if(!cellrow[k-1] && !cellrow[k+1]){
return false;
}
else{
return true;
}
}
}
boolean newCellValueByB(int k){//claculates the state of each cell by the last cellrow by rules of automaton B
if(cellrow[k]) {
if(!cellrow[k+1]){
return true;
}
else{
return false;
}
}
else{
if((!cellrow[k-1] && cellrow[k+1]) || (cellrow[k-1] && !cellrow[k+1])){
return true;
}
else{
return false;
}
}
}
void changeToNewRow() {//selects what rule will be used and makes the new cellrow
for(int i = 1; i < length - 1; i++){
if(automata == 'A'){
newCellrow[i] = newCellValueByA(i);
}
else if(automata == 'B'){
newCellrow[i] = newCellValueByB(i);
}
}
cellrow = newCellrow.clone();
}
void nextCellrow() {//draws the cellrow and jumps to the next cellrow
for(int i = 1; i < gen; i++){
draw();
changeToNewRow();
}
}
public static void main(String[] args) {
(new Cellulitis()).readGeneral();
(new Cellulitis()).readInitialConfiguration();
(new Cellulitis()).draw();
(new Cellulitis()).changeToNewRow();
(new Cellulitis()).nextCellrow();
}
}
这是我得到的错误:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at Cellulitis.readInitialConfiguration(Cellulitis.java:28)
at Cellulitis.main(Cellulitis.java:108)
我该如何解决这个问题?
提前致谢!
答案 0 :(得分:0)
正如答案中所见,问题是因为
app
必须改为
Scanner sc = new Scanner(System.in);