zoukankan      html  css  js  c++  java
  • Java知识系统回顾整理01基础04操作符07Scanner

    一、Scanner

    需要用到从控制台输入数据时,使用Scanner类。

       

    二、使用Scanner读取整数

    注意: 使用Scanner类,需要在最前面加上

    import java.util.Scanner;

    表示导入这个类,才能够正常使用

    导入类的语法:

    import 类的包名;

       

       

    import java.util.Scanner;

       

    public class HelloWorld {

        public static void main(String[] args) {

            Scanner s = new Scanner(System.in);

            int a = s.nextInt();

            System.out.println("第一个整数:"+a);

            int b = s.nextInt();

            System.out.println("第二个整数:"+b);

        }

    }

       

    三、使用Scanner读取浮点数

       

    import java.util.Scanner;

        

    public class HelloWorld {

        public static void main(String[] args) {

            Scanner s = new Scanner(System.in);

            float a = s.nextFloat();

            System.out.println("读取的浮点数的值是:"+a);

        }

    }

       

    四、使用Scanner读取字符串

       

    import java.util.Scanner;

        

    public class HelloWorld {

        public static void main(String[] args) {

            Scanner s = new Scanner(System.in);

            String a = s.nextLine();

            System.out.println("读取的字符串是:"+a);

        }

    }

       

    五、读取整数后,接着读取字符串

    需要注意的是,如果在通过nextInt()读取了整数后,再接着读取字符串,读出来的是回车换行:" ",因为nextInt仅仅读取数字信息,而不会读取回车换行" ".

       

    所以,如果在业务上需要读取了整数后,接着读取字符串,那么就应该连续执行两次nextLine(),第一次是取走回车换行,第二次才是读取真正的字符串

       

    import java.util.Scanner;

        

    public class HelloWorld {

        public static void main(String[] args) {

            Scanner s = new Scanner(System.in);

            int i = s.nextInt();

            System.out.println("读取的整数是"+ i);

            String rn = s.nextLine();

            String a = s.nextLine();

            System.out.println("读取的字符串是:"+a);

        }

    }

       

       

       

  • 相关阅读:
    git merge 和 git rebase 的使用场景
    Xcode 报错:解决 Could not attach to pid : "xx" 不重开工程的杀手锏
    软件设计模式的7条原则
    iOS开发信号量的使用
    利用SAMKeyChain生成唯一设备号
    iOS Fundation和CoreFoundation的对象转换内存管理权问题
    已有的PHP安装gd扩展
    centos7 编译安装 php7.4
    Nacos集群模式部署步骤
    搭建 Apache RocketMQ 单机环境
  • 原文地址:https://www.cnblogs.com/xlfcjx/p/10770357.html
Copyright © 2011-2022 走看看