Finding the Sum of a String of numbers seperated by operators - java

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.

Related

Integer printing wrong value

When converting an integer to int array, for example 123 to {1,2,3}, I am getting values {49,50,51}.
Not able to find what is wrong with my code.
public class Test {
public static void main(String [] args) {
String temp = Integer.toString(123);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
newGuess[i] = temp.charAt(i);
}
for (int i : newGuess) {
System.out.println(i);
}
}
}
Output:
49
50
51
charAt(i) will give you UTF-16 code unit value of the integer for example in your case, UTF-16 code unit value of 1 is 49.
To get integer representation of the value, you can subtract '0'(UTF-16 code unit value 48) from i.
public class Test {
public static void main(String [] args) {
String temp = Integer.toString(123);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
newGuess[i] = temp.charAt(i);
}
for (int i : newGuess) {
System.out.println(i - '0');
}
}
}
Output:
1
2
3
To add a little Java 8 niceties to the mix which allows us to pack everything up neatly, you can optionally do:
int i = 123;
int[] nums = Arrays.stream(String.valueOf(i).split(""))
.mapToInt(Integer::parseInt)
.toArray();
Here we get a stream to an array of strings created by splitting the string value of the given integer's numbers. We then map those into integer values with Integer#parseInt into an IntStream and then finally make that into an array.
temp.charAt(i) is basically returning you characters. You need to extract the Integer value out of it.
You can use:
newGuess[i] = Character.getNumericValue(temp.charAt(i));
Output
1
2
3
Code
public class Test {
public static void main(String [] args) {
String temp = Integer.toString(123);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
newGuess[i] = Character.getNumericValue(temp.charAt(i));
}
for (int i : newGuess) {
System.out.println(i);
}
}
}
As your interest is to get as an integer value of an string. Use the method parse int Integer.parseInt() . this will return as integer.
Example :
int x =Integer.parseInt("6"); It will return integer 6.

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

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.

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

Scrabble code in java

I have to write a scrabble code in java without the use of if/switch statements. this is what i have so far
public class Scrabble {
public static void main(String[] args) {
}
public static int computeScore(String word) {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int[] values = {1,3,3,2,1,4,2,4,1,8,5,1,3,1,3,3,10,1,1,1,1,4,4,8,4,10};
int sum = 0;
for(int i = 0; i <word.length();i++) {
????
}
return sum;
}
}
I need some help, I had the idea of finding the character inside the string and finding its value but not sure how to write it out. Any help will be great! Thanks!
Inside you for loop you would need to do the following:
sum += values[aplphabet.indexOf(word.charAt(i))];
So your loop should so something like:
for(int i = 0; i <word.length();i++) {
sum += values[aplphabet.indexOf(word.charAt(i))];
}
This will of course not handle any modifier tiles on the scrabble board.
Alternatively you can use a HashMap<char, int> to store your letters, so that accessing them is a bit easier:
public class Scrabble {
HashMap<char, int> alphabet;
public static void main(String[] args) {
//initialize the alphabet and store all the values
alphabet = new HashMap<char, int>();
alpahbet.put('A', 1);
alpahbet.put('B', 3);
alpahbet.put('C', 3);
//...
alpahbet.put('Z', 10);
}
public static int computeScore(String word) {
int sum = 0;
for(int i = 0; i <word.length();i++) {
//look up the current char in the alphabet and add it's value to sum
sum += alphabet.get(word.charAt(i));
}
return sum;
}
}

Categories

Resources