034、java常用类-Scanner类

来源:互联网 发布:陕西网络作家协会 编辑:程序博客网 时间:2024/06/16 06:29
一、String类概述及其构造方法1、Scanner类概述JDK5以后用于获取用户的键盘输入2、构造方法public Scanner(InputStream source)二、Scanner类的成员方法1、基本格式1)hasNextXxx()  判断是否还有下一个输入项,其中Xxx可以是Int,Double等。如果需要判断是否包含下一个字符串,则可以省略Xxx2)nextXxx()  获取下一个输入项。Xxx的含义和上个方法中的Xxx相同默认情况下,Scanner使用空格,回车等作为分隔符2、常用方法public int nextInt()public String nextLine()三、System类下有一个静态的字段:public static final InputStream in; 标准的输入流,对应着键盘录入。InputStream is = System.in;public class ScannerDemo {public static void main(String[] args) {// 创建对象Scanner sc = new Scanner(System.in);int x = sc.nextInt();System.out.println("x:" + x);}}四、 Scanner类的方法讲解常用的两个方法:public int nextInt():获取一个int类型的值public String nextLine():获取一个String类型的值举例:用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("你输入的数据有误");}}}