Scanner 类的使用

发布时间 2023-11-21 20:30:24作者: one_1

  Scaner 类可以处理控制台的输入和处理字符串。

  1.基本概念:

  如    "1    3      4     7 ”

  • 标记:1,3,4,7
  • 分隔符:空格“  ”

   2.常用方法:  

 

    next()                                  // 读入一个标记,标记之间以空格,多个空格或者回车换行等进行分隔。
    nextInt(),nextDouble().....             //读入标记并转化成相应的数据类型
    hasNext()                              //判断是否还有其他标记
    NextLine()                             //读入一行

  next()

        Scanner sc = new Scanner(System.in);
        String a = sc.next();
        String b = sc.next();
        String c = sc.next();
        String d = sc.next();
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        System.out.println(d);    

   nextInt()  

       Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        System.out.println(a+" "+b);  //int类型和字符串类相加,int类型自动转化成字符串类型

   nextLine()          

        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();
        System.out.println(line);

以行为分隔符

 

  hasNext()

 

        Scanner sc = new Scanner(System.in);
           while(sc.hasNext()) {
            int a = sc.nextInt();
            int b = sc.nextInt();
            System.out.println(a+b);

    3.个人总结与体会:

  1. 方便易用:Scanner 类提供了一种直观的方式来读取用户输入或文件中的数据。它提供了各种方法来读取不同类型的数据,如 nextLine()、nextInt()、nextDouble() 等。这使得开发人员可以轻松地读取所需的数据类型,而无需自己处理输入格式和转换。
  2. 灵活性强:Scanner 类可以与多种输入源配合使用。你可以使用它来读取键盘输入、文件中的数据或字符串中的数据。此外,Scanner 类还提供了各种方法来定制输入读取的方式,如设置分隔符、读取指定数量的字符等。这使得你可以根据需要灵活地处理不同的输入情况。