|
@@ -3,41 +3,39 @@ package pl.weeia;
|
|
|
import java.util.regex.Matcher;
|
|
import java.util.regex.Matcher;
|
|
|
import java.util.regex.Pattern;
|
|
import java.util.regex.Pattern;
|
|
|
|
|
|
|
|
-import static java.lang.Boolean.FALSE;
|
|
|
|
|
-import static java.lang.Boolean.TRUE;
|
|
|
|
|
-
|
|
|
|
|
public class Str {
|
|
public class Str {
|
|
|
|
|
|
|
|
- public int add(String s){
|
|
|
|
|
- if(s.equals("")){
|
|
|
|
|
- return 0;
|
|
|
|
|
|
|
+ public int add(String s) {
|
|
|
|
|
+ if (s.isEmpty()) {
|
|
|
|
|
+ return 0; // Pusty ciąg zwraca 0
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- if(inputStr(s) == FALSE){
|
|
|
|
|
- System.out.print("regex nie poprawny. ");
|
|
|
|
|
- return 0;
|
|
|
|
|
|
|
+ String delimiter = ",|\n"; // Domyślne delimitery
|
|
|
|
|
+ String numbers = s;
|
|
|
|
|
+
|
|
|
|
|
+ // Sprawdzanie, czy na początku znajduje się niestandardowy delimiter
|
|
|
|
|
+ if (s.startsWith("//")) {
|
|
|
|
|
+ Matcher matcher = Pattern.compile("//(.*?)\\n(.*)").matcher(s);
|
|
|
|
|
+ if (matcher.matches()) {
|
|
|
|
|
+ delimiter = Pattern.quote(matcher.group(1)); // Pobranie niestandardowego delimitera
|
|
|
|
|
+ numbers = matcher.group(2); // Pobranie liczbowej części ciągu
|
|
|
|
|
+ } else {
|
|
|
|
|
+ throw new IllegalArgumentException("Niepoprawny format wejściowy dla niestandardowego delimitera");
|
|
|
|
|
+ }
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- String[] liczby = s.split(",|\\n");
|
|
|
|
|
|
|
+ // Podział i obliczenie sumy
|
|
|
|
|
+ String[] liczby = numbers.split(delimiter);
|
|
|
int sum = 0;
|
|
int sum = 0;
|
|
|
- for(String liczba : liczby){
|
|
|
|
|
- sum += Integer.parseInt(liczba);
|
|
|
|
|
|
|
+ for (String liczba : liczby) {
|
|
|
|
|
+ if (!liczba.isEmpty()) { // Unikaj pustych wartości
|
|
|
|
|
+ try {
|
|
|
|
|
+ sum += Integer.parseInt(liczba);
|
|
|
|
|
+ } catch (NumberFormatException e) {
|
|
|
|
|
+ throw new IllegalArgumentException("Nieprawidłowy format liczby: " + liczba);
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
}
|
|
}
|
|
|
return sum;
|
|
return sum;
|
|
|
}
|
|
}
|
|
|
-
|
|
|
|
|
- public boolean inputStr(String s){
|
|
|
|
|
- String input = s;
|
|
|
|
|
-// String regex = "\\d+(\\n|,)\\d+(\\n|,)\\d+";
|
|
|
|
|
- String regex = "\\d+((\\n|,)\\d+){0,2}";
|
|
|
|
|
- Pattern pattern = Pattern.compile(regex);
|
|
|
|
|
- Matcher matcher = pattern.matcher(input);
|
|
|
|
|
-
|
|
|
|
|
- if (matcher.matches()) {
|
|
|
|
|
- return true;
|
|
|
|
|
- } else {
|
|
|
|
|
- return false;
|
|
|
|
|
- }
|
|
|
|
|
- }
|
|
|
|
|
-
|
|
|
|
|
}
|
|
}
|