简体   繁体   中英

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. 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. I think you want non-digits, so you could use \\\\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.

I would suggest using the function String.split() to seperate out the pieces which contain numbers and the pieces that do not. 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). 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 :

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. Then, the switch checks if it is a number or not :

  • if it is the case, the boolean isLetter takes the false value and we concatenate the char to the previous number if there was

  • 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.

// 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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