我们在牛客网上做题时会经常用到Scanner类,可能会因为没有正确使用Scanner类导致程序就无法通过,因此我对Java中的Scanner类及其使用进行了总结。
创建Scanner对象的基本语法:
Scanner input = new Scanner(System.in);
创建好对象后通过Scanner类的方法进行读取。其中方法nextByte()、nextShort()、nextInt()、nextLong()、nextFloat()、nextDouble()、next()等都称为标记读取方法。因为他们会读取用分隔符隔开的标记,默认分隔符是空格。可以使用useDelimiter(String regex)方法设置新的分隔符模式。一个标记方法首先跳过任意分隔符(默认为空格),然后读取一个以分隔符结束的标记。
标题重点讲述next()和nextLine()方法
1、next()和nextLine()方法都会读取一个字符串。但是两者又有区别:
next()方法:
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.next();
System.out.println(str);
}
}
运行结果:只打印了hello

nextLine()方法:
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.next();
System.out.println(str);
}
}
运行结果:hello world

next()和nextLine()的区别:
next()
- next()方法将输入有效字符之前的任意分隔符(默认空格)自动去掉。
- 输入有效字符之后的分隔符为结束符。
nextLine()
- 以Enter为结束符,返回回车之前的所有字符,包括空白。
- 可以输出带有空格的字符串。
2、为了避免输入错误,不要在nextByte()、nextShort()、nextInt()、nextLong()、nextFloat()、nextDouble()、next()之后使用nextLine()。
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int value = in.nextInt();
String str = in.nextLine();
int ret = in.nextInt();
System.out.println(value);
System.out.println(str);
System.out.println(ret);
}
}
键盘输入23回车,34回车,45回车,
运行结果:

由运行结果我们可以发现我们输入23回车,34回车后结果就输出了。输出结果多了一行空行。原因是标记读取方法nextInt()读取23,然后在分隔符处停止(这里的分隔符为回车键)。next Line()方法会在读取分隔符之后结束。然后返回行分隔符之前的字符串,行分隔符之前没有字符,所以str是空的。
1503

被折叠的 条评论
为什么被折叠?



