Scanner

package com.heima.scanner;

import java.util.Scanner;

public class Demon1_Scanner {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);	//创建一个Scanner 对象,键盘录入
		int s = sc.nextInt();		//将录入的整数存储在s中
		int s1 = sc.nextInt();
		System.out.println(s+"..."+s1);
		}
		}
		
package com.heima.scanner;

import java.util.Scanner;

public class Demon1_Scanner {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);	//创建一个Scanner 对象,键盘录入
		
		if(sc.hasNextInt()) {		//判断输入的数是否是整型
			int s = sc.nextInt();
			System.out.println(s);
		}else {
			System.out.println("输入类型错误");
		}

错误示范:

package com.heima.scanner;

import java.util.Scanner;

public class Demon2_scanner {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入一个整数");
		int s1 = sc.nextInt();
		System.out.println("请输入一个字符串");
		String s2 = sc.nextLine();
		System.out.println(s1+"..."+s2);
	}

}

在在这里插入图片描述在一个对象里输入一个整数和一个字符串,输入整数回车后会直接输出,因为nextInt()整型输入时,其实输入的是1和\r\n,而nextInt()方法只获取1就结束了,
而nextLine()是键盘录入字符串,只要遇到\r\n他就结束,所以nextInt()剩下的\r\n直接留给nextLine(),nextLine()直接结束。

解决方法一:
通过创建两个Scanner对象来实现

package com.heima.scanner;

import java.util.Scanner;

public class Demon2_scanner {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入一个整数");
		int s1 = sc.nextInt();
		Scanner sc1 = new Scanner(System.in);
		System.out.println("请输入一个字符串");
		String s2 = sc1.nextLine();
		System.out.println(s1+"..."+s2);
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值