Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Homework_Loops;
- import java.util.Scanner;
- public class PO11_WordOrNumber_3 {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int n = Integer.parseInt(scanner.nextLine());
- int num = 0;
- int numSum = 0;
- Character previous = ' ';
- String text = " ";
- StringBuilder sb = new StringBuilder();
- boolean isNumber = false;
- for (int i = 0; i < n; i++) {
- //read user input
- text = scanner.nextLine();
- //check if text contains only numbers
- isNumber = text.matches("[0-9]+");
- //if text contains only numbers
- if (isNumber) {
- if (previous == 'w') {
- System.out.println(sb);
- sb.setLength(0);
- }
- num = Integer.parseInt(text);
- numSum += num;
- previous = 'n';
- }
- //if text is a word
- if (!isNumber) {
- if (previous == 'n') {
- System.out.printf("%d\n", numSum);
- numSum = 0;
- }
- if (sb.length() != 0)
- sb.append('-');
- sb.append(text);
- previous = 'w';
- }
- }
- if (previous == 'w') {
- System.out.println(sb);
- }
- if (previous == 'n'){
- System.out.println(numSum);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment