繁体   English   中英

在Java中使用字符作为StringTokenizer的分隔符

[英]Using characters as a delimiter for StringTokenizer in Java

我正在编写一个程序,该程序接受由逗号分隔的数字列表的输入,并对这些数字的总数求和。 例如,我有字符串“ 10、20、30、40、50”

我想从字符串中分别提取每个数字,即“ 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);
}

请注意,stringtokenizer在普通模式下使用空格分隔数字和子字符串。 我的意思是使用此构造函数StringTokenizer(string)

但是您可以使用另一个构造函数使用strTokenizer分隔数字

StringTokenizer(String str, String delim)

您可以使用","作为delim参数,并且所有子字符串将根据","进行分隔,在此示例中锁定:

    String numbers = "10,20,30,40,50,60,70";
    StringTokenizer t = new StringTokenizer(numbers, ",");
    int sum=0;
    while (t.hasMoreTokens()) {
        sum+=Integer.parseInt(t.nextToken());
    }
    System.out.println("sum: " + sum);

您也可以只使用String类中的split(String regex)方法来完成此操作
这是为您提供的示例和解决方案。

    String numbers = "10,20,30,40,50,60,70";// all numbers

    String[] separated_numbers = numbers.split(",");// separate them by comma

    // calculating sum
    int sum = 0;
    for (String number : separated_numbers) {
        sum += Integer.parseInt(number);
    }
    // print sum
    System.out.println("sum: " + sum);

没有StringTokenizer构造函数或工厂方法可以更轻松地完成您想要的操作。 如果您必须具有StringTokenizer那么我认为没有更好的方法来获取一个,除非您可以调整定界符字符串中的字符。

你写了

我的目标是我希望程序将每个非数字字符用作StringTokenizer的分隔符。

但这似乎有点狭narrow。 似乎最重要的是令牌 ,而不是令牌生成器,如果确实如此,那么基于正则表达式的String.split()可能会提供令人满意的替代方案:

for (String token : input.split("[^0-9]+")) {
    int i = Integer.parseInt(token);

    // ...
}

从字面上看,您想要把所有非数字的内容视为定界符。

还有其他基于正则表达式的解决方案,例如使用匹配一个数字的模式来通过Matcher.find()遍历字符串。

您可以使用正则表达式执行此操作

do {
    String input = JOptionPane.showInputDialog("Enter a series of numbers separated by commas.");

    int total = 0;

    if ((input != null))
    {
        Matcher m = Pattern.compile("(-?[0-9]+.[0-9]*)+").matcher(input);
        // when using regex, the first group is always the full text, so we skip it.
        for (int i = 1; i<=matcher.groupCount(); i++) {
            total = total + Integer.parseInt(matcher.group(i));
        }
    } else {
        System.exit(0);
    }

    JOptionPane.showMessageDialog(null, "Total: " + total);

} while (true);

您可以将所有非数字字符替换为一个字符,然后使用split方法获得一个全数字数组。

    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
        {
            String[] characterTokens = input.split("[^0-9]+");
            for (String characterToken : characterTokens) {
                input.replace(characterToken, ",");
            }
            String[] numberTokens = input.split(",");
            for (String numberToken: numberTokens) {
                total += Integer.parseInt(numberToken);
            }
        } 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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM