java中Scanner类nextInt之后用nextLine无法读取输入

 

问题描述:

 

String another = "y";
	Scanner scan = new Scanner(System.in);
	while (another.equalsIgnoreCase("y")) {
	System.out.println("请输入年份:");			
	int year = scan.nextInt();
	System.out.println("是否再次测试(Y/N)");
	 another=scan.nextLine();System.out.println(another+"测试");}

 

 

 

 

当我这样写输出是否再次测试(Y/N)可是我却无法输入任何东西,于是输出变量another ,发现变量改变,此时another="\n";

解决方法:

 

.nextLine();不能放在in.nextInt();代码段后面

否则.nextLine();会读入"\n"字符,但"\n"并不会成为返回的字符,将\n认为键入的字符!!!

 

方案一:

 

在another前加一个变量ch用于接收"\n"

 

 

String ch=scan.nextLine();
System.out.println("是否再次测试(Y/N)");
another=scan.nextLine();

 

 

 

 

 

方案二:

使用.next()

 

System.out.println("是否再次测试(Y/N)");another=scan.next();next();这个函数会扫描从有效字符起到空格,Tab,回车等结束字符之间的内容并作为String返回。nextLine();这个函数在你输入完一些东西之后按下回车则视为输入结束,输入的内容将被作为String返回。

next();这个函数与之不同在于,next();什么都不输入直接敲回车不会返回,而nextLine()即使不输入东西直接敲回车也会返回。

 

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// abc 123 def 456
String str1 = scan.nextLine();System.out.println("str1: "+str1);
String str2 = scan.next();
System.out.println("str2: "+str2);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值