martin_tsv
martin_tsv

Reputation: 39

How to sum the numbers and multiply it by the count of their sequence(Java)?

The input comes from the console as a single line, holding the numbers. After each number i have a character(S, H, D or C). Need to sum the numbers and only when two or more characters come sequentially, to multiply the sum by the count of the character’s sequence.

For example, 2C 3C 5C 15S 10H 12H 2S 14D has value (2 + 3 + 5) * 3 + 15 + (10 + 12) * 2 + 2 + 14 = 105.

I can only extract and sum the numbers, but nothing more.

public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String[] input = br.readLine().split(" ");
        int sum = 0;

        for (String s : input) {
            String number = s.substring(0, s.length() - 1);
            sum += Integer.parseInt(number);
        }
        System.out.println(sum);
}    

Thanks in advance!

Upvotes: 0

Views: 359

Answers (1)

user8344665
user8344665

Reputation:

This will do the trick

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    String[] input = br.readLine().split(" "); 
    int sum = 0;
    String tmpLetter = null;
    int tmpSum = 0;
    int count = 0;

    for (String s : input) { 
        int number = Integer.parseInt(s.substring(0, s.length() - 1));
        String letter = s.substring(s.length() - 1);

        if(tmpLetter == null || tmpLetter.equals(letter)){
            count++;
            tmpSum += number;
        } else {
            sum += tmpSum * count;
            count = 1;
            tmpSum = number;
        }
        tmpLetter = letter;
    }
    sum += tmpSum * count;
    System.out.println(sum);
}

Upvotes: 1

Related Questions