大家好,以下代码欲接收用户输入的5个数字,然后再打印出来。对用户的输入做了异常处理,但一运行起来,输入了一个数字之后,就开始不停地打印异常信息:请输入第2个数字:
java.util.NoSuchElementException
请问这段代码问题出在哪里?
- import java.util.*;
- public class TestPrint {
- public static void main(String[] args) {
- ArrayList<Integer> arrayNumber = new ArrayList<Integer>();
- for (int i = 0; i != 5; ++i) {
- int nNumber = getUserInputSeconds(i + 1);
- arrayNumber.add(nNumber);
- }
-
- for (Integer i : arrayNumber) {
- System.out.println(i + " ");
- }
- }
-
- // 接收输入,非法时提示重新输入
- private static int getUserInputSeconds(int nIndex) {
- int nSeconds = 0;
- while (true) {
- System.out.printf("请输入第%d个数字:\n", nIndex);
- boolean bInputSuccess = true;
- try {
- nSeconds = doGetInputSeconds();
- } catch (Exception e) {
- System.out.println(e.toString());
- bInputSuccess = false;
- }
- finally {
- if (bInputSuccess) {
- break;
- }
- }
- }
- return nSeconds;
- }
-
- private static int doGetInputSeconds() throws Exception {
- Scanner s = new Scanner(System.in);
- int nSeconds = s.nextInt();
- s.close();
- return nSeconds;
- }
- }
复制代码
|
|