zoukankan      html  css  js  c++  java
  • java之Scanner

    参考http://how2j.cn/k/operator/operator-scanner/658.html#nowhere

    需要用到从控制台输入数据,所以需要用到Scanner类

    使用Scanner读取整数

    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);
        }
    }
  • 相关阅读:
    EXE中释放文件
    关闭GS选项,解决注入后崩溃
    HDU2516 取石子游戏
    HDU2188 选拔志愿者
    HDU2149 Public Sale
    HDU2147 kiki's game
    HDU1846 Brave Game
    LightOJ1214 Large Division
    POJ2480 Longge's problem
    HDU 5880 Family View
  • 原文地址:https://www.cnblogs.com/lijingran/p/9128227.html
Copyright © 2011-2022 走看看