Java Scanner中的next(), nextLine(), nextInt()

本文详细介绍了Java Scanner类的next(), nextLine(), nextInt()等方法的用法和特点。next()返回由分隔符包围的完整标记,nextLine()跳过当前行并返回不包括行结束符的输入,nextInt()扫描下一个整数。理解这些方法对于正确处理Scanner输入至关重要。" 133518958,19453851,Python中去除字符串两端空格的方法,"['Python', '字符串处理']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JavaScanner中的next()

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
【注1】这里的delimiter pattern默认是正则表达式:\p{javaWhitespace}+,表示匹配任何空白字符,因此next()读取的内容默认去掉前后的空白符号;
【注2】可以通过,例如sc.useDelimiter(Pattern.compile(";"));这样来改变默认的delimiter pattern;这里sc表示Scanner的一个对象。

public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	sc.useDelimiter(Pattern.compile(";"));
	System.out.println("The delimiter used is "+sc.delimiter());
	System.out.println(sc.next());
}
JavaScanner中的hasNext()

Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.
【注】第三句直译为不会超前越过输入数据,也就是说等待输入数据。

JavaScanner中的nextLine()

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
【注1】通过line separator分割每一行的输入;
【注2】停留在下一行的开头。
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.

JavaScanner中的hasNextLine()

Returns true if there is another line in the input of this scanner. This method may block while waiting for input. The scanner does not advance past any input.
【注】和hasNext()明显不同的是,hasNextLine()这里是line,用line separator分割, “In any UNIX systems, line separator will return “\n” or a positive integer; and on Windows systems it returns “\r\n” or a positive integer.”;而hasNext()是用delimiter pattern分割,默认是若干个空格。

JavaScanner中的nextInt()

Scans the next token of the input as an int.
If the translation is successful, the scanner advances past the input that matched.
【注】粗体的第二句话表示,读入这个int之后,scanner会越过这个int,但是注意,不会越过line separator,因此如果之后的语句是nextLine()的话,则会读入一个line separator,即一个换行符。所以,如果要读取下一行字符串的话,应该使用两个nextLine()


JavaScanner中的nextDouble()

Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.

参考Java Scanner官方文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值