的StringTokenizer的定界符我寫一個程序,它用逗號隔開,總人數的合計數值列表的輸入。例如,我有字符串「10,20,30,40,50」使用字符在Java中
我想從字符串中分別提取每個數字「10」「20」「30」「40」「50」數字列表的總和。
我找到了一個解決方案,但是,我發現我的代碼有點亂,當我回去看看吧,我會在一分鐘內不少「WTF」的。
所以,
我想知道是否有寫下面一行更好的辦法:
StringTokenizer inputTokenizer = new StringTokenizer(input, "- ,\\n\\r\\t\\b\\fabcdefghijklmnopqrstuvwxyz");
我的目標是我想要的程序使用的每個字符是一個非數字作爲StringTokenizer的分隔符。 因此,例如串"11abc33"
應該分成"11"
和"33"
。
這裏是什麼,我想出了
public static void main(String[] args) {
do {
//Prompts user to enter a series of numbers and stores it in the String "input"
String input = JOptionPane.showInputDialog("Enter a series of numbers separated by commas.");
//total stores the sum of each number entered
int total = 0;
if ((input != null)) //checks if the user didn't cancel or quit the program
{
//sets every alphabetical character in the input String to lowercase
input = input.toLowerCase();
//creates a StringTokenizer that uses commas and white spaces as delimiters
StringTokenizer inputTokenizer = new StringTokenizer(input, "- ,\\n\\r\\t\\b\\fabcdefghijklmnopqrstuvwxyz");
//sums the total of each number entry
while (inputTokenizer.hasMoreTokens()) {
total = total + Integer.parseInt(inputTokenizer.nextToken());
}
} else {
//exit the program because the user hit cancel or exit
System.exit(0);
}
//display the sum of the total number entries
JOptionPane.showMessageDialog(null, "Total: " + total);
} while (true);
}
所以你想分割一個輸入字符串使用空格或數字之間的逗號? –
是或任何非數字字符 –
如果您只想分割逗號,則分隔符看起來很複雜。如果你確實想要使用所有的分隔符,你可能想要檢查一下String.split()方法,並使用regex來表達所有那些更清晰的語法。 –