MagdalenaTakeva

PO11_WordOrNumber_3

Feb 15th, 2022
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. package Homework_Loops;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class PO11_WordOrNumber_3 {
  6. public static void main(String[] args) {
  7. Scanner scanner = new Scanner(System.in);
  8. int n = Integer.parseInt(scanner.nextLine());
  9. int num = 0;
  10. int numSum = 0;
  11. Character previous = ' ';
  12. String text = " ";
  13. StringBuilder sb = new StringBuilder();
  14. boolean isNumber = false;
  15.  
  16.  
  17. for (int i = 0; i < n; i++) {
  18. //read user input
  19. text = scanner.nextLine();
  20.  
  21. //check if text contains only numbers
  22. isNumber = text.matches("[0-9]+");
  23.  
  24. //if text contains only numbers
  25.  
  26. if (isNumber) {
  27. if (previous == 'w') {
  28. System.out.println(sb);
  29. sb.setLength(0);
  30. }
  31. num = Integer.parseInt(text);
  32. numSum += num;
  33. previous = 'n';
  34.  
  35. }
  36.  
  37. //if text is a word
  38. if (!isNumber) {
  39. if (previous == 'n') {
  40. System.out.printf("%d\n", numSum);
  41. numSum = 0;
  42. }
  43.  
  44. if (sb.length() != 0)
  45. sb.append('-');
  46. sb.append(text);
  47. previous = 'w';
  48. }
  49.  
  50. }
  51.  
  52.  
  53. if (previous == 'w') {
  54. System.out.println(sb);
  55. }
  56.  
  57.  
  58. if (previous == 'n'){
  59. System.out.println(numSum);
  60. }
  61. }
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment