return the sum of all integers - java

Program should return sum of all the numbers in a string.
public static void main(String[] args) {
String data = "1a2b-3c";
data=data.replaceAll("[\\D]+"," ");
String[] numbers=data.split(" ");
int sum = 0;
for(int i=0;i<numbers.length;i++){
try{
sum+=Integer.parseInt(numbers[i]);
}
catch( Exception e ) {
e.printStackTrace();
}
}
System.out.println("The sum is:"+sum);
}
So for the above input, it should return sum as 0 ==> (1+2 - 3)
But my above code returns 6. What is the right regex for this?

Here's how you should do it
String data = "1a2b-3c";
int sum=0;
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(data);
while (m.find()) {
sum+=Integer.parseInt(m.group());
}

A simple way would be to do this.
if(numbers[i - 1].equals('-')){
  sum-=Integer.parseInt(numbers[i]);
} else
sum+=Integer.parseInt(numbers[i]);

Use the split tool on your String, splitting every symbol individually into an array , then just add the numbers with parseInt and you're done. No need for a pattern here I think.

Related

How to differentiate numbers and strings

I have a string
String s="Raymond scored 2 centuries at an average of 34 in 3 innings.";
I need to find the sum of only numbers present in the string without encountering any exceptions. Here the sum should be 2+34+3=39. How to make the compiler understand the differences between String and Integer.
You should split input string by spaces (or by regex, it's unclear from your question) to the array of String tokens, then iterate through this array. If Integer.parseInt(token) call doesn't produce the NumberFormatException exception then it returns an integer, which you should add to the numbers list for further processing (or add to the sum right away)
String inputString = "Raymond scored 2 centuries at an average of 34 in 3 innings.";
String[] stringArray = inputString.split(" ");//may change to any other splitter regex
List<Integer> numbers = new ArrayList<>();
for (String str : sArr) {
try {
numbers.add(Integer.parseInt(str)); //or may add to the sum of integers here
} catch (NumberFormatException e){
System.out.println(e);
}
}
//todo any logic you want with the list of integers
You should split the string using a regex expression. The split will be made between all non digits characters. Here is a sample code:
String text = "there are 3 ways 2 win 5 games";
String[] numbers = text.split("\\D+");
int sum = 0;
for (String number : numbers) {
try {
sum += Integer.parseInt(number);
} catch (Exception ex) {
//not an integer number
}
}
System.out.println(sum);
public void sumOfExtractedNumbersFromString(){
int sum=0;
String value="hjhhjhhj11111 2ssasasa32sas6767676776767saa4sasas";
String[] num = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" };
for(char c : value.toCharArray())
{
for (int j = 0; j < num.length; j++) {
String val=Character.toString(c);
if (val.equals(num[j])) {
sum=sum+Integer.parseInt(val);
}
}
}
System.out.println("Sum"+sum);`
}
public class MyClass {
public int addition(String str){
String[] splitString = str.split(" ");
// The output of the obove line is given below but now if this string contain
//'centuries12' then we need to split the integer from array of string.
//[Raymond, scored, 2, centuries12, at, an, average, of, 34, in, 3, innings]
String[] splitNumberFromSplitString= str.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
// The output of above line is given below this regular exp split the integer
// number from String like 'centuries12'
// [Raymond scored,2,centuries,12, at an average of,34, in , 3, innings]
int sum=0;
for (String number : splitNumberFromSplitString) {
if(StringUtils.isNumeric(number)){
sum += Integer.parseInt(number);
}
}
return sum;
}
public static void main(String args[]) {
String str = "Raymond scored 2 centuries at an average of 34 in 3 innings";
MyClass obj = new MyClass();
int result = obj.addition(str);
System.out.println("Addition of Numbers is:"+ result);
}
}
Output :
Addition of Numbers is:39
Well there are multiple ways on how to solve your problem. I assume that you are only looking for integers (otherwise each of the solutions may be adaptable to also look for floating numbers).
Using regular expressions:
public static int sumByRegEx(final String input) {
final Pattern nrPattern = Pattern.compile("\\d+");
final Matcher m = nrPattern.matcher(input);
int sum = 0;
while (m.find()) {
sum += Integer.valueOf(m.group(0));
}
return sum;
}
Using a Scanner:
public static int sumByScanner(final String input) {
final Scanner scanner = new Scanner(input);
int sum = 0;
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
sum += scanner.nextInt();
} else {
scanner.next();
}
}
scanner.close();
return sum;
}
Using String methods:
public static int sumByString(final String input) {
return Stream.of(input.split("\\s+"))
.mapToInt(s -> {
try {
return Integer.valueOf(s);
} catch (final NumberFormatException e) {
return 0;
}
}).sum();
}
All cases return the correct results (as long as null is not passed):
public static void main(final String[] args) {
final String sample = "Raymond scored 2 centuries at an average of 34 in 3 innings.";
// get some 39:
System.out.println(sumByRegEx(sample));
System.out.println(sumByScanner(sample));
System.out.println(sumByString(sample));
// get some 0:
System.out.println(sumByRegEx(""));
System.out.println(sumByScanner(""));
System.out.println(sumByString(""));
// some "bad" examples, RegEx => 10, Scanner => 0, String => 0
System.out.println(sumByRegEx("The soccer team is playing a 4-3-3 formation."));
System.out.println(sumByScanner("The soccer team is playing a 4-3-3 formation."));
System.out.println(sumByString("The soccer team is playing a 4-3-3 formation."));
}
i think you should write a different function to check either it is a number or not for good as good practices:
public class SumOfIntegersInString {
public static void main(String[] args) throws ClassNotFoundException {
String s = "Raymond scored 2 centuries at an average of 34 in 3 innings.";
String[] splits= s.split(" ");
System.out.println(splits.length);
int sum = 0;
for (int j=0;j<splits.length;j++){
if (isNumber(splits[j]) == true){
int number = Integer.parseInt(splits[j]);
sum = sum+number;
};
};
System.out.println(sum);
};
public static boolean isNumber(String string) {
try {
Integer.parseInt(string);
} catch (Exception e) {
return false;
}
return true;
}
}
No fancy tricks: check if each character is a digit and if so parse/add it.
public static void SumString (string s)
{
int sum = 0, length = s.length();
for (int i = 0; i < length; i++)
{
char c = s.charAt(i);
if (Character.isDigit(c))
sum += Integer.parseInt(c);
}
return sum;
}

Split values from string and get the sum of these values

I want to split the amount value from a string I got from txt file, the problem is the split value is string and even after parsing it to integer I can't accumulate the summation of it.
Here is the main method:
public static void main(String[] args) throws IOException {
String file_name = "C:\\application\\TestFile2.txt";
try {
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
int i;
for (i=0;i<aryLines.length;i++)
{
//System.out.println(aryLines[i]);
//////split each line to get the total amount
String[] parts = aryLines[i].split("\\|");
String amount = parts[5];
System.out.println(amount);
}
/////count total number of lines
System.out.println(file.readLines());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
Why are you doing num = num ++?
You should keep sum = 0 outside and sum += num in the loop;
Finally println(sum)
Your question is not clear to me. Can you please give an example of the String you want to split and what summation you want after splitting ?
Ok u can do something like this -
List<Integer> amt=new ArrayList<Integer>();
for(int i=0;i<aryLines.length;i++){
String arr[]=aryLines[i].split("\\|");
amt.add(Integer.parseInt(arr[5])); //assuming 6th position contains the amount.
}
Object amtArr[]=amt.toArray();
int sum=0;
for(int j=0;j<amtArr.length;j++){
sum=sum+(Integer)amtArr[j];
}
System.out.println("Sum is: "+sum);

How to test the string to see if it contains two integers and if it does I need to use them in the acker function

This is what I have so far, if the string has two integers I need to pull them out and use them in the acker function that takes in two integers as parameters.
public static void main(String []args)
{
String nextLine = "";
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
AckerFunction x = new AckerFunction();
System.out.println("Input two integers separated by a space character (enter q to quit):");
try {
nextLine = input.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
if (nextLine.matches("[0-9]+") && nextLine.length() > 2)
{
x.acker(m, n)
}
I suppose you want to get two integers from console. Use nextInt() method like in the code shown below.
public static void main(String[] args) {
AckerFunction x = new AckerFunction();
Scanner input = new Scanner(System.in);
System.out.println("Input two integers separated by a space character");
try {
int m = input.nextInt();
int n = input.nextInt();
x.acker(m,n);
}
catch(InputMismatchException e) {
System.out.println("Incorrect input, please enter integers");
}
finally {
input.close();
}
}
First, you can use .Split() method to split the string into an array to have direct access to any of the elements/numbers. Just an example:
String str = "123 456";
char c = ' ';
String[] s = str.Split(c);
double[] nums = new double[str.Length]
for(int i=0; i<s.Length; i++)
{
double d;
if(Double.TryParse(s[i], out d))
nums[i] = d;
}
Just added some check so you won't have errors. If it's not a number, it'd stay null.
This will extract the first two integers from a string and ignore all other characters. If you only want to get two numbers from the console prudhvi has the right answer.
String regex = "-?\\d+";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(nextLine);
int i = 0;
int[] val = new int[2];
while( matcher.find() && i++ < 2 )
val[i-1] = Integer.valueOf(matcher.group());
if( i == 2 )
x.acker(val[0], val[1]);

java program to return the sum of all integers found in the parameter String

i want write a java program to return the sum of all integers found in the parameter String.
for example take a string like:" 12 hi when 8 and 9"
now the answer is 12+8+9=29.
but i really dont know even how to start can any one help in this!
You may start with replacing all non-numbers from the string with space, and spilt it based on the space
String str = "12 hi when 8 and 9";
str=str.replaceAll("[\\D]+"," ");
String[] numbers=str.split(" ");
int sum = 0;
for(int i=0;i<numbers.length;i++){
try{
sum+=Integer.parseInt(numbers[i]);
}
catch( Exception e ) {
//Just in case, the element in the array is not parse-able into Integer, Ignore it
}
}
System.out.println("The sum is:"+sum);
You shall use Scanner to read your string
Scanner s = new Scanner(your string);
And then read it using
s.nextInt();
Then add these integers.
Here is the general algorithm:
Initialize your sum to zero.
Split the string by spaces, and for each token:
Try to convert the token into an integer.
If no exception is thrown, then add the integer to your sum.
And here is a coding example:
int sumString(String input)
{
int output = 0;
for (String token : input.split(" "))
{
try
{
output += Integer.parseInt(token);
}
catch (Exception error)
{
}
}
return output;
}
private static int getSumOfIntegersInString(String string) {
/*Split the String*/
String[] stringArray = string.split(" ");
int sum=0;
int temp=0;
for(int i=0;i<stringArray.length;i++){
try{
/*Convert the numbers in string to int*/
temp = Integer.parseInt(stringArray[i]);
sum += temp;
}catch(Exception e){
/*ignore*/
}
}
return sum;
}
You could use a regular expression
Pattern p = Pattern.compile("\\d+");
String s = " 12 hi when 8 and 9" ;
Matcher m = p.matcher(s);
int start = 0;
int sum=0;
while(m.find(start)) {
String n = m.group();
sum += Integer.parseInt(n);
start = m.end();
}
System.out.println(sum);
This approach does not require the items to be separated by spaces so it would work with "12hiwhen8and9".
Assume your words are separated by whitespace(s):
Then split your input string into "tokens"(continuous characters without whitespace).
And then loop them, try to convert each of them into integer, if exception thrown, means this token doesn't represents a integer.
Code:
public static int summary(String s) {
String[] tokens = s.split("\\s+");
int sum = 0;
for(String token : tokens) {
try {
int val = Integer.parseInt(token);
sum += val;
}
catch(NumberFormatException ne){
// Do nothing
}
}
return sum;
}
String s ="12 hi when 8 and 9";
s=s.replaceAll("[^0-9]+", " ");
String[] numbersArray= s.split(" ");
Integer sum = 0;
for(int i = 0 ; i<numbersArray.length;i++){
if(numbersArray[i].trim().length() != 0){
Integer value = Integer.valueOf(numbersArray[i].trim());
sum = sum + value;
}
}
System.out.println(sum);
You can have a look on the following code :-
public class Class02
{
public static void main(String[] args)
{
String str = "12 hi when 8 and 9";
int sum = 0;
List<String> list = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(str.toLowerCase());
while(st.hasMoreElements())
{
list.add(st.nextToken());
}
for(int i =0; i< list.size();i++)
{
char [] array = list.get(i).toCharArray();
int num = array[0];
if(!(num >= 'a' && num <= 'z'))
{
int number = Integer.valueOf((list.get(i).toString()));
sum = sum + number;
}
}
System.out.println(sum);
}
}
Hope it will help you.
I understand that this does not have the Java8 tag but I will put this out there in case someone finds it interesting
String str = "12 hi when 8 and 9";
System.out.println(Arrays.stream(str.split(" "))
.filter(s -> s.matches("[0-9]+")).mapToInt(Integer::parseInt).sum());
would nicely print out 29

java comparing the first 2 characters

I want to find in a Text the starting is number followed by .
example:
1.
11.
111.
My code for x. ( x is number) this is working . issue is when x is more than 2 digits.
x= Character.isDigit(line.charAt(0));
if(x)
if (line.charAt(1)=='.')
How can I extend this logic to see if x is a integer followed by .
My first issue is :
I need to fond the given line has x. format or not where x is a integr
You can use the regex [0-9]\. to see if there exists a digit followed by a period in the string.
If you need to ensure that the pattern is always at the beginning of the string you can use ^[0-9]+\.
Why not using a regular expression?
([0-9]+)[.]
You can use regex:
Pattern.compile("C=(\\d+\\.\\d+)")
However, more general would be:
Pattern.compile("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?")
Now to work with the Pattern you do something like:
Pattern pattern = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?");
Matcher matcher = pattern.matcher(EXAMPLE_TEST);
// Check all occurances
while (matcher.find()) {
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end() + " ");
System.out.println(matcher.group());
}
Edit: Whoops, misread.
try this:
public static boolean prefix(String s) {
return s.matches("[0-9]+\\.");
}
public class ParsingData {
public static void main(String[] args) {
//String one = "1.";
String one = "11.";
int index = one.indexOf(".");
String num = (String) one.subSequence(0, index);
if(isInteger(num)) {
int number = Integer.parseInt(num);
System.out.println(number);
}
else
System.out.println("Not an int");
}
public static boolean isInteger(String string) {
try {
Integer.valueOf(string);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}

Categories

Resources