java之Scanner

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

须要用到从控制台输入数据,因此须要用到Scanner类java

使用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);
    }
}

执行程序spa

使用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);
 
    }
}

执行程序code

使用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()读取了整数后,再接着读取字符串,读出来的是回车换行:"\r\n",由于nextInt仅仅读取数字信息,而不会读取回车换行"\r\n".

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

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);
    }
}
相关文章
相关标签/搜索