I used
int num = Integer.parseInt(str)
to written integer values into a string.I need a function that reads these values from given string and calculates their sum.
Example: input - "43 68 9 23 318" output - 461
I used
int num = Integer.parseInt(str)
to written integer values into a string.I need a function that reads these values from given string and calculates their sum.
Example: input - "43 68 9 23 318" output - 461
String str = "43 68 9 23 318";
int num = Integer.parseInt(str)
What you are doing is, trying to parse the complete input string at once, that will throw the NumberFormatException
. You need to split it first and then perform the sum on each returned String
.
Split the input string by whitespace
then parse each number and perform the sum.
public static void main(String[] args) {
String input = "43 68 9 23 318";
String numbers[] = input.split("\\s+"); // Split the input string.
int sum = 0;
for (String number : numbers) { // loop through all the number in the string array
Integer n = Integer.parseInt(number); // parse each number
sum += n; // sum the numbers
}
System.out.println(sum); // print the result.
}
In Java 8, using streams
String input = "43 68 9 23 318";
String numbers[] = input.split("\\s+");
int[] nums = Arrays.stream(numbers.substring(1, numbers.length()-1).split(","))
.map(String::trim).mapToInt(Integer::parseInt).toArray();
int sum = IntStream.of(nums).sum();
System.out.println("The sum is " + sum);
Another Java 8 way:
public void test() {
String str = "43 68 9 23 318";
int sum = Pattern.compile(" ")
.splitAsStream(str)
.mapToInt(Integer::parseInt)
.sum();
System.out.println("sum:" + sum);
}
You can try following with java-8. Here we first split the String
to get String[]
with number String
(i.e ["43", "68", "9", "23", "318"]
) and then with the help of Arrays.stream
we can map all those Strings
to Integer
and we will have IntStream
and from that we can get sum
of all streamed Integer
values.
public class Test {
public static void main(String[] args) {
String input = "43 68 9 23 318";
int sum = Arrays.stream(input.trim().split("\\s+"))
.mapToInt(Integer::parseInt)
.sum();
System.out.println(sum);
}
}
OUTPUT
461
If you don't want to go to the hassle of splitting it you can do it in-place:
public void test() {
String str = "43 68 9 23 318";
int sum = 0;
int value = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
switch (ch) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = value * 10 + (ch - '0');
break;
default:
sum += value;
value = 0;
break;
}
}
// Remember the last number.
sum += value;
value = 0;
System.out.println("sum:" + sum);
}
This is the needed Working copy with function
public class Main {
/*This function is static because we called it from static main*/
public static int returnSum(String str)
{
String []numbStr = str.split(" ");
int sum = 0;
for(String temp:numbStr)
{
sum += Integer.parseInt(temp);
}
return sum;
}
public static void main(String... args)
{
String str = "43 68 9 23 318";
/*Note that we can call only static functions from main when directly calls*/
int result = returnSum(str);
System.out.println(result);
}
}
Java 8 Streams in one line
Arrays.stream(text.split(" ")).mapToInt(Integer::parseInt).sum();
This works not only for the strings that contains numbers separated by spaces but also for the strings containing characters others than numbers like "abc10jh20"-->30
import java.util.Arrays.*;
public class HelloWorld{
//this code works also if the string contains alphabets not just spaces
static int count,sum;
public static void main(String []args){
String str="123 10 7";//getting input in form of string
int length=str.length();
for(int i=0;i<=length-1;i=i+count+1)
{
count=0;
if(Character.isDigit(str.charAt(i)))
{
for(int j=i;j<=length-1;j++)
{
if(Character.isDigit(str.charAt(j)))
{
count++;//to find the length of the number
}
else{
break;
}
}
String str2=str.substring(i,i+count);//selecting the substring
System.out.println("the parsing string "+str2);//displays strings getting parsed
int inc=count+1;
sum=sum+Integer.parseInt(str2);//finding sum
}
}
System.out.println("the sum is "+sum);
}
}