程序源代码如下,报错是在getStartNum()方法,有两个方法都用到Scanner获得参数,第一个方法能够获得,到第二个就不行了。错误信息放在下面。
package zeng.javatest;
import java.util.Scanner;
public class Josephus {
private int getCrimerNum() {
int crimerNum = 0;
System.out.println("输入犯人的数量:");
Scanner sc = new Scanner(System.in);
crimerNum = sc.nextInt();
sc.close();
return crimerNum;
}
private int getStartNum() {
int startNum = 0;
System.out.println("输入从几号开始计数:");
Scanner sc = new Scanner(System.in);
startNum = sc.nextInt();
sc.close();
return startNum;
}
private int getCount() {
int counter = 0;
System.out.println("输入一个count:");
Scanner sc = new Scanner(System.in);
counter = sc.nextInt();
sc.close();
return counter;
}
private int[] init(int n) {
int a[] = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = i + 1;
}
return a;
}
private boolean countCrimerNum(int a[]) {
int count = 0;
for (int i = 0; i < a.length; i++) {
if(a[i] == 0){
count ++;
}
}
if (count < (a.length - 1)) {
return true;
}
else return false;
}
private int[] killCrimer(int a[], int s, int d) {
int index = 0;
int n = a.length;
index = (s+d)%n;
a[index] = 0;
System.out.println("第"+(index + 1)+"个犯人被处刑");
return a;
}
public static void main(String[] args) {
int n = 0, s = 0, d = 0;
Josephus jj = new Josephus();
n = jj.getCrimerNum();
s = jj.getStartNum();
d = jj.getCount();
int crimer[] = new int[n];
crimer = jj.init(n);
while(jj.countCrimerNum(crimer)){
crimer = jj.killCrimer(crimer, s, d);
s = (s + d)%n;
}
}
}
eclipse下的报错信息:
输入犯人的数量:
5
输入从几号开始计数:
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 zeng.javatest.Josephus.getStartNum(Josephus.java:20)
at zeng.javatest.Josephus.main(Josephus.java:71)
------解决方案--------------------
用全局变量。。
import java.util.Scanner;
public class Josephus {
static Scanner sc = null;