1.问题:
这是今天写东西的时候遇到的问题,当我运行下列代码时,str会读取到回车从而使str自己是空白内容,所以我上网查询了一下,以下是一些小小的总结:
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int b=sc.nextInt();
String str=sc.nextLine();
在实际输入过程中,str是读取不到的,如下图所示:
对于上述问题,我总结了以下三种解决方法:
🌈方法一:
重新创建Scanner对象,重写创建对象之后换行符会被丢弃:
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int b=sc.nextInt();
Scanner sc1=new Scanner(System.in);
String str=sc1.nextLine();
🌈方法二:
在读入字符串之前先将回车用nextLine()读取掉,操作如下:
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int b=sc.nextInt();
sc.nextLine();//先读取掉回车 在读取str
String str=sc.nextLine();
🌈方法三:
使用next():
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int b=sc.nextInt();
String str=sc.next();
下面简述一下next() 与 nextLine() 区别:
next(): next()会自动消去有效字符前的空格,只返回输入的字符,不能得到带空格的字符串。
nextLine(): nextLine()方法返回的是Enter键之前的所有字符,它是可以得到带空格的字符串的,可以得到空白。
本文含有隐藏内容,请 开通VIP 后查看