黑马程序员技术交流社区

标题: Scanner 类问题(大神进) [打印本页]

作者: 名字被注册了    时间: 2016-9-23 22:27
标题: Scanner 类问题(大神进)
String[] chinese = {"零","一","二","三","四","五","六","七","八","九"};
Scanner sc = new Scanner(System.in);
                while (true) {
                        System.out.println("请输入一个大于-1且小于1000的正整数");
                        try {
                                int num = sc.nextInt();
                                //print(num,chinese);
                                break;
                        } catch (Exception e) {
                                System.out.println("输入错误");
                        }                       
                }       
请大神回答:为什么报错?解决办法,为什么?
作者: 名字被注册了    时间: 2016-9-23 22:30
补充:需要输入异常数据!
作者: gcno93    时间: 2016-9-23 23:56
public static void main(String[] args) {
                String[] chinese = {"零","一","二","三","四","五","六","七","八","九"};
                 InputStream in = System.in;
                while (true) {
            System.out.println("请输入一个大于-1且小于1000的正整数");
            try {
                    Scanner sc = new Scanner(in);
                        int num = sc.nextInt();
                break;
            } catch (Exception e) {
                    System.out.println("输入错误");
            }                       
        }  
        }
作者: gcno93    时间: 2016-9-23 23:59
public class Demo2 {
        public static void main(String[] args) {
                String[] chinese = {"零","一","二","三","四","五","六","七","八","九"};
                Scanner sc = new Scanner(System.in);
                String temp ="";//临时存取键盘输入的
                while (true) {
            System.out.println("请输入一个大于-1且小于1000的正整数");
            temp = sc.nextLine();
            try {
                        int num = Integer.parseInt(temp);
                          //print(num,chinese);
                break;
            } catch (Exception e) {
                    System.out.println("输入错误");
            }                       
        }  
        }
作者: gcno93    时间: 2016-9-24 00:01
gcno93 发表于 2016-9-23 23:56
public static void main(String[] args) {
                String[] chinese = {"零","一","二","三","四","五","六"," ...

  InputStream in = System.in;可以用 Scanner sc = new Scanner(System.in);代替,我是测试一下为什么才这样写的,可是还是找不出




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2