JustJinnyThings
JustJinnyThings

Reputation: 37

summing all numbers in string without .split()

Currently, my code work only with single digit numbers. Example: if I enter 5 3 2 the output will be

Sum: 10
Product: 30

However, if I enter double digit numbers, they get treated as each individual digit. Example: if I enter 11 12 13 the output will be

Sum: 9
Product: 6

Here is my code:

package scanner;

import java.util.Scanner;

public class NumberScanner {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter some numbers, enter '.' to terminate");
        String scannedString = input.nextLine();
        while (scannedString.charAt(0) != '.') {
            scanAndPrint(scannedString);
            System.out.println("Enter more numbers");
            scannedString = input.nextLine();
        }
        input.close();
    }

    public static void scanAndPrint(String scannedString) {
        System.out.println("Numbers:" + scannedString);
        int sum = 0;
        int prod = 1;
        String num = "";
        for (int n = 0; n < scannedString.length(); n++) {
            num = scannedString.substring(n, n + 1) + "";
            if (Character.isDigit(scannedString.charAt(n))) {
                sum = sum += Integer.parseInt(scannedString.charAt(n) + "");
                prod = prod *= Integer.parseInt(scannedString.charAt(n) + "");
            }
        }
        System.out.println("Sum:" + sum);
        System.out.println("Product:" + prod);
    }
}

I am trying to do this without using .split().

Conceptually, I'm pretty sure I should loop through each character of the string and concatenate each character into a String variable. In other words, store all the characters between spaces into a variable (create own .split() ) How would I go about this?

Upvotes: 3

Views: 202

Answers (3)

Andreas
Andreas

Reputation: 159086

For the more lazy developer, use a regular expression, assuming that counts as "without .split()".

The following code has full error checking, which is missing from both question and other answers.

public static void main(String[] args) {
    Pattern p = Pattern.compile("\\s*(\\d+)\\s*");
    Scanner input = new Scanner(System.in);
    System.out.println("Enter some numbers, enter '.' to terminate");
    while (true) {
        String line = input.nextLine();
        if (line.trim().equals("."))
            break;
        int start = 0;
        int sum = 0;
        long prod = 1;
        for (Matcher m = p.matcher(line); m.find() && m.start() == start; start = m.end()) {
            try {
                int number = Integer.parseInt(m.group(1));
                sum += number;
                prod *= number;
            } catch (NumberFormatException e) {
                break; // prints "invalid text" since start < line.length()
            }
        }
        if (start != line.length()) {
            System.out.println("Found invalid text: " + line.substring(start));
        } else {
            System.out.println("Sum:" + sum);
            System.out.println("Product:" + prod);
        }
    }
}

Upvotes: 2

Alfonso Presa
Alfonso Presa

Reputation: 1034

You should sum when you find a space or the end of the line. An accumulate in a string when you find a number:

  for (int n = 0; n < scannedString.length(); n++) {
   //Get the character
   char c = scannedString.charAt(n);

   //If it's a digit we accumulate it in an string called num
   if (Character.isDigit(scannedString.charAt(n))) {
    num += Character.toString(c);
   //Otherwise we perform the sum and prod
   } else if(!num.isEmpty()){
    sum = sum += Integer.parseInt(num);
    prod = prod *= Integer.parseInt(num);
    num = "";
   }
  }

  //We should also add and prod the last number.
  if(!num.isEmpty()){
   sum = sum += Integer.parseInt(num);
   prod = prod *= Integer.parseInt(num);
  }

The only different thing to do is sum and multiply at the end also just in case the last number was not added because the loop ended before finding an space character

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

In order to work with multi-digit numbers your code needs to detect number boundaries correctly. Your current implementation places a boundary after each digit, which is what is causing your problem.

Specifically, adding 1 on this line is wrong:

num = scannedString.substring(n, n+1);

you should be adding the number of digits in the number that starts at position n. Here is one way of doing it:

for(int n = 0 ; n < scannedString.length() ; /* yes, empty! */ ) {
    // Ignore non-digit characters
    if (!Character.isDigit(scannedString.charAt(n))) {
        n++;
        continue;
    }
    // char at position n is a digit; try the next one,
    // then the next, until the string ends or you find a non-digit:
    int len = 1;
    while (n+len < scannedString.length() && Character.isDigit(scannedString.charAt(n+len))) {
        len++;
    }
    // At this point len is the length of the next number string.
    // Take the substring, and parse it:
    int num = Integer.parseInt(scannedString.substring(n, n+len));
    // Advance sum and prod. Note that there is no redundant assignment.
    sum += num;
    prod *= num;
    // Advance the loop index inside the body
    n += len;
}

Upvotes: 5

Related Questions