64.5k views
3 votes
Write a method that takes three numerical String values and sums their values.

For example, the call sumStrings("1", "5", "7") would return 13.

This is in Java.

2 Answers

5 votes

Answer:

Is in the provided screenshot!

Step-by-step explanation:

All we need to do is use the built in function "parseInt" to turn a String into an Integer, then we can just add these and return it from the function!

I've also added some basic exception handling - if any one of the numbers aren't written in correctly then the program will just return '-1' instead of crashing.

Write a method that takes three numerical String values and sums their values. For-example-1
User Eusthace
by
3.9k points
6 votes

Answer:

Algorithm:

  1. Take a int variable c=0.
  2. Run the loop from 0 to String length.
  3. Get the each index value using charAt() method which will return the char value.
  4. Convert that char into int by typecasting or any other way.
  5. Now check that ASCII fall into the range of 48-57 for 0-9 int number.
  6. If it matches then first convert that number into integer using Integer.parseInt().
  7. Then add with the c and store to the same variable i.e c.
  8. Repeat from 3-7 till the end of the loop.
  9. At the end of loop , Print c outside the loop.

Step-by-step explanation:

// Java program to calculate sum of all numbers present

// in a string containing alphanumeric characters

class GFG

{

// Function to calculate sum of all numbers present

// in a string containing alphanumeric characters

static int findSum(String str)

{

// A temporary string

String temp = "";

// holds sum of all numbers present in the string

int sum = 0;

// read each character in input string

for(int i = 0; i < str.length(); i++)

{

char ch = str.charAt(i);

// if current character is a digit

if (Character.isDigit(ch))

temp += ch;

// if current character is an alphabet

else

{

// increment sum by number found earlier

// (if any)

sum += Integer.parseInt(temp);

// reset temporary string to empty

temp = "0";

}

}

// atoi(temp.c_str()) takes care of trailing

// numbers

return sum + Integer.parseInt(temp);

}

// Driver code

public static void main (String[] args)

{

// input alphanumeric string

String str = "1abc5yz7";

System.out.println(findSum(str));

}

}

User Pyuntae
by
3.7k points