A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 月影千华 中级黑马   /  2015-10-24 00:02  /  700 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. import java.util.Scanner;

  2. public class Test3 {
  3.     public static void main(String[] args) {
  4.         while (true) {
  5.             System.out.println("input number:");
  6.             Scanner sc = new Scanner(System.in);
  7.             int x = sc.nextInt();
  8.             sc.close();
  9.             System.out.println(x);
  10.         }
  11.     }
  12. }
复制代码
请问为什么会报NoSuchElementException的错误,把 sc.close()注释掉就不会报错了,但是我想不通的是,每次循环,不是重新开打流了吗,为什么会报错?


1 个回复

倒序浏览
import java.util.Scanner;

public class Test2 {
        public static void main(String[] args) {
                Scanner sc = new Scanner(System.in);
                int x = 0;
                while (true) {
                        System.out.println("input number:");
                        x = sc.nextInt();
                        System.out.println(x);
                }
        }
}
把close那句去掉就行了,然后可以把变量的定义放在while外面,减少内存消耗~虽然耗得不多
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马