英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论