Java API ——Scanner类

1、Scanner类概述

  JDK5以后用于获取用户的键盘输入,一个可以使用正则表达式来解析基本类型和字符串的简单文本扫描器。Scanner 使用分隔符模式将其输入分解为标记,默认情况下该分隔符模式与空白匹配。然后可以使用不同的 next 方法将得到的标记转换为不同类型的值。
2、现在使用的构造方法
        public Scanner(InputStream source)
3、Scanner类的成员方法
  1)基本格式
    hasNextXxx()  判断是否还有下一个输入项,其中Xxx可以是Int,Double等。如果需要判断是否包含下一个字符串,则可以省略Xxx。
    nextXxx()  获取下一个输入项。Xxx的含义和上个方法中的Xxx相同。
  2)默认情况下,Scanner使用空格,回车等作为分隔符
   3)举例:用int类型的方法举例
    public boolean hasNextInt()
    public int nextInt()
public class ScannerDemo {
    public static void main(String[] args) {
        // 创建对象
        Scanner sc = new Scanner(System.in);
        // 获取数据,先判断输入的数据是否与接收的变量的类型匹配
        if (sc.hasNextInt()) {
            int x = sc.nextInt();
            System.out.println("x:" + x);
        } else {
            System.out.println("你输入的数据有误");
        }
    }
}
  4)分析以下两个方法的组合使用:
        public int nextInt()
        public String nextLine()
        如果先获取一个数值,再获取一个字符串,会出现问题。主要原因:就是那个换行符号的问题。
        问题解决:
            A:先获取一个数值后,在创建一个新的键盘录入对象获取字符串。
     B:把所有的数据都先按照字符串获取,然后要什么,你就对应的转换为什么。
public class ScannerDemo {
    public static void main(String[] args) {
        // 创建对象
        Scanner sc = new Scanner(System.in);
        // 获取两个int类型的值
        int a1 = sc.nextInt();
        int b1 = sc.nextInt();
        System.out.println("a:" + a1 + ",b:" + b1);
        System.out.println("-------------------");
        // 获取两个String类型的值
        String s1 = sc.nextLine();
        String s2 = sc.nextLine();
        System.out.println("s1:" + s1 + ",s2:" + s2);
        System.out.println("-------------------");
        // 先获取一个字符串,在获取一个int值
        String s3 = sc.nextLine();
        int b2 = sc.nextInt();
        System.out.println("s1:" + s3 + ",b:" + b2);
        System.out.println("-------------------");
        // 先获取一个int值,在获取一个字符串,数据获取有误
        int a2 = sc.nextInt();
        String s4 = sc.nextLine();
        System.out.println("a:" + a2 + ",s2:" + s4);
        System.out.println("-------------------");
        //解决方法:定义两个Scanner对象,分别获取两次数据
        int a = sc.nextInt();
        Scanner sc2 = new Scanner(System.in);
        String s = sc2.nextLine();
        System.out.println("a:" + a + ",s:" + s);
    }
}

 

 
posted @ 2015-11-03 19:28  我是一名老菜鸟  阅读(2711)  评论(0编辑  收藏  举报