简体   繁体   English

java - 如何从包含数字和字母的序列中添加数字?

[英]How to add numbers from a sequence that contains numbers and letters in java?

lets say the user submits this sequence: dadeer50dfder625dsf3 , the program should print the result of the sum of the numbers : 50+625+3.假设用户提交这个序列:dadeer50dfder625dsf3,程序应该打印数字总和的结果:50+625+3。 How can i do this ?我怎样才能做到这一点 ?

This is what i have done so far, but its not working.这是我到目前为止所做的,但它不起作用。 Can someone help me please :( :有人能帮助我吗 :( :

String secuencia = JOptionPane.showInputDialog("Ingresa tu secuencia");
           int par = secuencia.length();
                     int sumatoria = 0;
         int sumatoria1 = 0;
                          for (int i = 0; i < par; i++) {
            String p = secuencia.substring(i, i +1); 
                        if(p.equals("1") || p.equals("2") || p.equals("3") || p.equals("4") || p.equals("5") || p.equals("6") || p.equals("7") || p.equals("8") || p.equals("9") || p.equals("0")){
                                for (int j = i + 1; j < par; j++) {
                                String n = secuencia.substring(j, j + 1);
                                 if(n.equals("1") || n.equals("2") || n.equals("3") || n.equals("4") || n.equals("5") || n.equals("6") || n.equals("7") || n.equals("8") || n.equals("9") || n.equals("0")){

                                     int v = Integer.parseInt(p);
                                     int y = Integer.parseInt(n);
                          sumatoria += v;       
                                     sumatoria1 += y ;

                        }      }}           

                        System.out.print(sumatoria);
                        System.out.println(sumatoria1);

You could String.split(String) , which takes a regular expression.你可以String.split(String) ,它需要一个正则表达式。 I think you want non-digits, so you could use \\\\D+ .我认为你想要非数字,所以你可以使用\\\\D+ Something like,就像是,

String str = "dadeer50dfder625dsf3";
String[] arr = str.split("\\D+");
int total = 0;
StringBuilder sb = new StringBuilder();
for (String val : arr) {
    if (val.isEmpty()) {
        continue;
    }
    sb.append(val).append(" + ");
    total += Integer.parseInt(val);
}
sb.replace(sb.length() - 2, sb.length(), "= ");
System.out.print(sb);
System.out.println(total);

And the output is输出是

50 + 625 + 3 = 678

Roberto,罗伯托,

It looks like you are on the right path, however the problem with your code is that it assumes the number is only a single character long.看起来您走在正确的道路上,但是您的代码的问题在于它假定数字只有一个字符长。 I think it adds 5+0+6+2+5+3 instead of the desired add.我认为它添加了 5+0+6+2+5+3 而不是所需的添加。

I would suggest using the function String.split() to seperate out the pieces which contain numbers and the pieces that do not.我建议使用函数 String.split() 将包含数字的部分和不包含数字的部分分开。 I believe you can pass something like [A-Za-z] and that will return strings that only contain numbers in them(Assuming only letters and not other characters are used).我相信你可以传递像 [A-Za-z] 这样的东西,它会返回只包含数字的字符串(假设只使用字母而不使用其他字符)。 http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String) http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)

Here's a simple code without using RegEx's like you told us in the commentaries :这是一个简单的代码,没有像您在评论中告诉我们的那样使用 RegEx:

public static void main(String[] args) {
    String str = "55blhalhalh3265hezubf565";
    boolean isLetter = false;
    String temp = "";
    int sum = 0;

    for (int i = 0 ; i < str.length() ; i++){
        switch(str.charAt(i)){
        case '0': 
        case '1': 
        case '2': 
        case '3': 
        case '4': 
        case '5': 
        case '6': 
        case '7': 
        case '8': 
        case '9':
            isLetter = false;
            temp += str.charAt(i);
            break;
        default :
            if (!isLetter)sum += Integer.parseInt(temp);
            isLetter = true;
            temp = "";
            break;
        }
    }
    if (!isLetter) sum += Integer.parseInt(temp);

    System.out.println("The final sum is " + sum);
}

I made the switch long on purpose to be very clear.我故意让开关长得很清楚。

A little explanation :一点解释:

The for iterates over all the chars of your String object of course. for会遍历String对象的所有字符。 Then, the switch checks if it is a number or not :然后, switch检查它是否是一个数字:

  • if it is the case, the boolean isLetter takes the false value and we concatenate the char to the previous number if there was如果是这样,布尔值 isLetter 取假值,如果有,我们将字符连接到前一个数字

  • if it is a letter, we add the already found number to the total sum.如果它是一个字母,我们将已经找到的数字添加到总和中。

Here are two versions.这里有两个版本。
The first shows how easy it is when using regular expression.第一个显示使用正则表达式是多么容易。
The second uses the constraints given in a comment.第二个使用注释中给出的约束。 Since it said "substring", I'll assume that using Integer.parseInt() is ok.由于它说“子字符串”,我假设使用Integer.parseInt()

// Using regular expression
String text = "dadeer50dfder625dsf3";
int sum = 0;
for (Matcher m = Pattern.compile("\\d+").matcher(text); m.find(); )
    sum += Integer.parseInt(m.group());
System.out.println(sum);

// Using only substring, for loops and length
String text = "dadeer50dfder625dsf3";
int sum = 0, numStart = -1;
for (int i = 0; i < text.length(); i++) {
    char c = text.charAt(i);
    if (c >= '0' && c <= '9') {
        if (numStart == -1)
            numStart = i;
    } else {
        if (numStart != -1)
            sum += Integer.parseInt(text.substring(numStart, i));
        numStart = -1;
    }
}
if (numStart != -1)
    sum += Integer.parseInt(text.substring(numStart));
System.out.println(sum);

Output from both两者的输出

678
String str = "dadeer50dfder625dsf3";
    List<String> list = Arrays.asList(str.split("\\D+"));
    int sum = 0;
    for (String each : list) {
        try {
            sum += Integer.parseInt(each);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    System.out.println(sum);

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

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