JAVA之Scanner类

JAVA第十天之Scanner类的方法

1.Scanner类简单方法:
public class MyTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        nextXXX 系列的方法
        sc.nextInt();//接收int类型的数据
        sc.nextDouble();//接收double类型的数据
        sc.nextLine();//接收字符串 可包含有空格
        sc.next();//接收任意数据,但是接收字符串时 若字符串之间有空格则只接收部分
        sc.hasNextXxx();//判断一个是否是某种类型的元素, 其中Xxx可以是Int, Double,line等,如果要判断的是字符串则可以省略Xxx;
   }
2. ①注意事项:当先录入一个其他类型的数,这个时候再去使用nextLine()录入字符串的时候,会发现不需要录入程序就停止了,原因是 输入完第一个数后 按了回车换行 但是这个时候 回车换行默认被录入 nextLine()中
public class MyTest {
    public static void main(String[] args) {  
    Scanner sc = new Scanner(System.in);
	System.out.println(“请输入一个整数”);
	int i=sc.nextInt();
	System.out.println(i);
	System.out.println(“请输入一个字符串”);
	String s=sc.nextLine();
	System.out.println(s);
}

解决方法:重新new 一个对象再去接收 或者 用next()接收 next()默认会忽略掉回车换行

public class MyTest {
    public static void main(String[] args) {  
    Scanner sc = new Scanner(System.in);
	System.out.println(“请输入一个整数”);
	int i=sc.nextInt();
	System.out.println(i);
	System.out.println(“请输入一个字符串”);
	//sc=new Scanner(System.in);
	String s=sc.nextLine();
	//String s=sc.next();
	System.out.println(s);
}
②:注意事项: nextLine()与next()的区别

nextLine(); // 输入的字符串 之间可以带有空格

next();//输入的字符串之间如果有空格则只输入第一个空格前的内容

代码示例:

public class MyTest {
    public static void main(String[] args) {  
    Scanner sc = new Scanner(System.in);
	System.out.println(“请输入一个字符串”);
	String s=sc.nextLine();
	//String s=sc.next();
	System.out.printfln(s);
}

运行结果:
在这里插入图片描述
在这里插入图片描述

3.Scanner类方法的应用
public class MyTest {
    public static void main(String[] args) {
        scanner();
    }
    public static void scanner(){
        Scanner sc = new Scanner(System.in);                                                                                           
        System.out.println("请输入一个整数");
        if(sc.hasNextInt()){
            int i = sc.nextInt();
            System.out.println(i);
        }else{
            System.out.println("你输入的类型不正确,请重新输入");
            scanner();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值