本文介绍了如何使用点作为定界符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import java.util.Scanner;
public class Test{
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        input.useDelimiter(".");
        String given = input.next();
        System.out.println(given);
    }
}

当我运行上面的代码并键入 asdf。然后输入,我什么也没得到。

When I run the above code and type in asdf. then enter, I get nothing.

与, ; \ \\ \\ 或其他任何东西,但不能与一起使用。 ...一个点是否存在某些东西,或者仅仅是一个Eclipse IDE或其他问题导致问题?

It works fine with "," ";" "\"" "\\\\" or whatever, but just not with "."... So is there something about a dot or is it just a problem with Eclipse IDE or whatever?

推荐答案

扫描仪正在使用正则表达式(regex)作为分隔符和是特殊字符,表示除行以外的任何字符因此,如果在编写 asdf时定界符是任何字符,每个定界符都将被视为定界符,而不仅仅是点。您将使用 next()结果将是空字符串,该字符串存在于我标记为 |

Scanner is using regular expression (regex) as delimiter and dot . in regex is special character which represents any character except line separators. So if delimiter is any character when you write asdf. each of its character will be treated as delimiter, not only dot. So each time you will use next() result will be empty string which exists in places I marked with |

a|s|d|f|.

要创建点文字,您需要对其进行转义。您可以使用 \。。还有其他方法,例如使用 [。] 。

To create dot literal you need to escape it. You can use \. for that. There are also other ways, like using character class [.].

所以尝试

input.useDelimiter("\\.");

这篇关于如何使用点作为定界符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 17:48