How to differentiate numbers and strings - java

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;
}

Related

Finding the Sum of a String of numbers seperated by operators

Given String = "128+16+8+2+1"
Answer should print out 155
The code is supposed to add all numbers in the string and the answer should be printed out as a string.
I attempted to write the code for this, however the last 2 numbers will not add and my current answer is printing out 153. Looking for help to lead me to the correct solution.
import java.util.stream.*;
public class add {
static void evalA(String s) {
int n = countChar(s,'+');
System.out.println(s);
int cnt = 0;
int[] data = new int[n];
for(int i=0;i<s.length();i++) {
if (s.charAt(i)=='+') {
System.out.println(s.substring(0,i));
data [cnt] = Integer.parseInt(s.substring(0,i));
cnt++;
s = s.substring(i+1,s.length()-1);
i=0;
}
}
String sum = ""+IntStream.of(data).sum();
System.out.println(sum);
}
}
You could do something like this:
public static void main(String[] args)
{
evaluate("128+16+8+2+1");
}
public static void evaluate(String equation)
{
String[] numbers = equation.split("\\+");
int sum = 0;
for (String number : numbers)
{
//could wrap this in a check incase of exception or errors
sum += Integer.parseInt(number);
}
System.out.println(sum);
}
It just splits the string up by the + to get the individual numbers as an array and then loop through the array and add each numbers value to a sum variable.

Summing the ints in a string using scanner.chopper: java

first post on this site, so, I essentially have to find a way to chop up the ints in a string, divided only by spaces, (example would be ("9 10 5 20 1 2 3") and then find the sum of all of the chopped up ints. I know i have to use chopper.nextInt(), but I am not sure how to format the totality of the code, along with summing the output after. Thanks so much!
import static java.lang.System.*;
import java.util.Scanner;
public class LineTotaller
{
private String line;
public LineTotaller()
{
setLine("");
}
public LineTotaller(String s)
{setLine(s);
}
public void setLine(String s)
{line = s;
}
public int getSum()
{
int sum = 0;
Scanner chopper = new Scanner(line);
while(chopper.hasNextInt())
{
out.print(chopper.nextInt());
sum+= //returned ints from above
}
}
public String getLine()
{
return "";
}
public String toString()
{
return getLine();
}
}
I think you want to do the following
public int getSum()
{
int sum = 0;
Scanner chopper = new Scanner(line);
while(chopper.hasNextInt())
{
int nextInt = chopper.nextInt();
System.out.print(nextInt);
sum += nextInt;
}
return sum;
}
You can only call nextInt once after you confirmed that there is something via hasNextInt. If you want to print it and add it to the sum, you have to store the value temporarily in a variable.
Consider using the string.split() method to place you numbers string into a string array then iterate through the array with a 'for loop', convert each element to a integer ( Integer.valueOf() )and maintain a ongoing total with each iteration.
Something like:
String yourString = "9 10 5 20 1 2 3";
String[] myNumbers = yourString.split(" ");
int total = 0;
for (int i = 0; i < myNumbers.length; i++) {
total+= Integer.valueOf(myNumbers[i]);
}
System.out.println("Total is: -> " + total);
That should get it done for you.

return the sum of all integers

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.

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

interviewstreet.com - String similarity

I'm trying to solve the string similarity question on interviewstreet.com. My code is working for 7/10 cases (and it is exceeding the time limit for the other 3).
Here's my code -
public class Solution {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String v1 = user_input.next();
int number_cases = Integer.parseInt(v1);
String[] cases = new String[number_cases];
for(int i=0;i<number_cases;i++)
cases[i] = user_input.next();
for(int k=0;k<number_cases;k++){
int similarity = solve(cases[k]);
System.out.println(similarity);
}
}
static int solve(String sample){
int len=sample.length();
int sim=0;
for(int i=0;i<len;i++){
for(int j=i;j<len;j++){
if(sample.charAt(j-i)==sample.charAt(j))
sim++;
else
break;
}
}
return sim;
}
}
Here's the question -
For two strings A and B, we define the similarity of the strings to be the length of the longest prefix common to both strings. For example, the similarity of strings "abc" and "abd" is 2, while the similarity of strings "aaa" and "aaab" is 3.
Calculate the sum of similarities of a string S with each of it's suffixes.
Input:
The first line contains the number of test cases T. Each of the next T lines contains a string each.
Output:
Output T lines containing the answer for the corresponding test case.
Constraints:
1 <= T <= 10
The length of each string is at most 100000 and contains only lower case characters.
Sample Input:
2
ababaa
aa
Sample Output:
11
3
Explanation:
For the first case, the suffixes of the string are "ababaa", "babaa", "abaa", "baa", "aa" and "a". The similarities of each of these strings with the string "ababaa" are 6,0,3,0,1,1 respectively. Thus the answer is 6 + 0 + 3 + 0 + 1 + 1 = 11.
For the second case, the answer is 2 + 1 = 3.
How can I improve the running speed of the code. It becomes harder since the website does not provide a list of test cases it uses.
I used char[] instead of strings. It reduced the running time from 5.3 seconds to 4.7 seconds and for the test cases and it worked. Here's the code -
static int solve(String sample){
int len=sample.length();
char[] letters = sample.toCharArray();
int sim=0;
for(int i=0;i<len;i++){
for(int j=i;j<len;j++){
if(letters[j-i]==letters[j])
sim++;
else
break;
}
}
return sim;
}
used a different algorithm. run a loop for n times where n is equals to length the main string. for each loop generate all the suffix of the string starting for ith string and match it with the second string. when you find unmatched character break the loop add j's value to counter integer c.
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Solution {
public static void main(String args[]) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(in.readLine());
for (int i = 0; i < T; i++) {
String line = in.readLine();
System.out.println(count(line));
}
}
private static int count(String input) {
int c = 0, j;
char[] array = input.toCharArray();
int n = array.length;
for (int i = 0; i < n; i++) {
for (j = 0; j < n - i && i + j < n; j++)
if (array[i + j] != array[j])
break;
c+=j;
}
return c;
}
}
I spent some time to resolve this question, and here is an example of my code (it works for me, and pass thru all the test-cases):
static long stringSimilarity(String a) {
int len=a.length();
char[] letters = a.toCharArray();
char localChar = letters[0];
long sim=0;
int sameCharsRow = 0;
boolean isFirstTime = true;
for(int i=0;i<len;i++){
if (localChar == letters[i]) {
for(int j = i + sameCharsRow;j<len;j++){
if (isFirstTime && letters[j] == localChar) {
sameCharsRow++;
} else {
isFirstTime = false;
}
if(letters[j-i]==letters[j])
sim++;
else
break;
}
if (sameCharsRow > 0) {
sameCharsRow--;
sim += sameCharsRow;
}
isFirstTime = true;
}
}
return sim;
}
The point is that we need to speed up strings with the same content, and then we will have better performance with test cases 10 and 11.
Initialize sim with the length of the sample string and start the outer loop with 1 because we now in advance that the comparison of the sample string with itself will add its own length value to the result.
import java.util.Scanner;
public class StringSimilarity
{
public static void main(String args[])
{
Scanner user_input = new Scanner(System.in);
int count = Integer.parseInt(user_input.next());
char[] nextLine = user_input.next().toCharArray();
try
{
while(nextLine!= null )
{
int length = nextLine.length;
int suffixCount =length;
for(int i=1;i<length;i++)
{
int j =0;
int k=i;
for(;k<length && nextLine[k++] == nextLine[j++]; suffixCount++);
}
System.out.println(suffixCount);
if(--count < 0)
{
System.exit(0);
}
nextLine = user_input.next().toCharArray();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Categories

Resources