英文:
Is there a way to advance the scanner only a by a single or n amount of characters in Java?
问题
给出一个例子,假设你有一个时间:20:30,你只想知道那个时间的分钟部分(我知道你可以使用 LocalTime.parse()
,然后使用 getMinute()
,但请记住,这只是一个例子,假装你不能为秒数这样做),有没有一种方法可以将扫描器仅前进一定数量的行,然后在到达分钟部分时调用 nextInt()
?到目前为止,我知道的所有扫描方法都只会扫描到空格或换行符为止。
英文:
To give one example what if you had a time: 20:30 and you only want to know the minutes of that time (I know you can use LocalTime.parse()
and then getMinute()
, but keep in mind, this is just an example, so please pretend you can't do that for second), is there a way to advance the scanner only a certain number of lines and then invoke nextInt()
once you reach the minutes part? every method of scanning I know so far only scans until a whitespace or newline.
答案1
得分: 1
你可以在扫描器上设置分隔符。
Scanner input = new Scanner(System.in);
input.useDelimiter(":|\\r");
int hr = scanner.nextInt();
int min = scanner.nextInt();
int sec = scanner.nextInt();
System.out.println(hr + " " + min + " " + sec);
对于输入 10:21:34
输出
10 21 34
英文:
You can set the delimiter on a scanner.
Scanner input = new Scanner(System.in);
input.useDelimiter(":|\r");
int hr = scanner.nextInt();
int min = scanner.nextInt();
int sec = scanner.nextInt();
System.out.println(hr + " " + min + " " + sec);
For input of 10:21:34
Prints
10 21 34
</details>
# 答案2
**得分**: 1
如果你知道要向前移动多少个字符,可以使用 [`skip`](https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#skip(java.lang.String)) 方法。
例如,如果你想跳过 100 个字符:
```java
scanner.skip("?(s).{100}");
如果你想要跳过 5 行:
scanner.skip("(?:.+(?:\r\n|[\n\r\u2028\u2029\u0085])){5}");
如果你不知道要跳过多少个字符,只想找到下一个类似时间的子字符串,可以使用 findWithinHorizon
方法:
String timeString = scanner.findWithinHorizon("\\d\\d:\\d\\d", 0);
// 然后你可以使用 LocalTime.parse 来解析 timeString
英文:
If you know how many characters you want to advance, use skip
.
For example, if you want to skip 100 characters:
scanner.skip("(?s).{100}");
If you want to skip 5 lines instead,
scanner.skip("(?:.+(?:\r\n|[\n\r\u2028\u2029\u0085])){5}");
If you don't know how many characters to skip, and just want to find the next substring looks like a time, use findWithinHorizon
:
String timeString = scanner.findWithinHorizon("\\d\\d:\\d\\d", 0);
// then you can use LocalTime.parse to parse "timeString"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论