Java方法以从用户获取分隔符。

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

Java method to get separator from user

问题

我正在编写我的程序中的这个方法,用于将文本文件解析为XML。用户提供文件的分隔符。文件可以用逗号、冒号、制表符或管道分隔。下面的方法适用于逗号,但不适用于其他3种分隔符。提前感谢您的帮助。

public static String getSeparator(String separator) {
    Scanner userInput = new Scanner(System.in);

    do {
        System.out.println("输入分隔符类型(逗号、冒号、制表符、管道)");
        separator = userInput.nextLine();
    } while (!separator.equals(",") && !separator.equals(":") && !separator.equals("\t") && !separator.equals("|"));

    return separator;
}
英文:

I'm writing this method in my program that parses text files to XML. The user provides the separator of the file. The file might be separated by comma, colon, tab, or pipe. The method below works for comma but not the other 3. Thanks in advance for the help.

public static String getSeparator(String separator) {
    Scanner userInput = new Scanner(System.in);

    do {
        System.out.println("Enter the separator type (commas, Colons, Tabs, Pipes)");
        separator = userInput.nextLine();
    } while (!separator.equals(",") || separator.equals(":") || separator.equals("   ") || separator.equals("|"));

    return separator;
}

答案1

得分: 1

你需要在整个条件周围使用括号。

while (!(separator.equals(",") || separator.equals(":") || separator.equals("   ") || separator.equals("|")));

更好的方式是定义一个字符串数组来存储分隔符:

String[] separators = new String[] {",", ":", "   ", "|"};

然后检查它是否在列表中:

} while (!Arrays.asList(separators).contains(separator));
英文:

You need to use a parentheses around the whole condition.

while (!(separator.equals(",") || separator.equals(":") || separator.equals("   ") || separator.equals("|")));

Better way is to define an String array of the seperators:

String[] seperators = new String[] {",",":"," ","|"};

And then check if it is in list:

} while (!Arrays.asList(seperators).contains(seperator));

</details>



huangapple
  • 本文由 发表于 2020年10月25日 09:25:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/64519511.html
匿名

发表评论

匿名网友

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

确定