在Java中,是否有一种方法可以将扫描器仅按单个字符或n个字符前进?

huangapple go评论75阅读模式
英文:

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(&quot;(?s).{100}&quot;);

If you want to skip 5 lines instead,

scanner.skip(&quot;(?:.+(?:\r\n|[\n\r\u2028\u2029\u0085])){5}&quot;);

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(&quot;\\d\\d:\\d\\d&quot;, 0);
// then you can use LocalTime.parse to parse &quot;timeString&quot;

huangapple
  • 本文由 发表于 2020年9月25日 08:07:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/64056010.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定