I'm trying to make a program that takes Ints and give me sum and I want to make it using regex. Input contains numbers, symbols and letters. For example when I write: java GiveMeSum 4 2 1 -5 or java GiveMeSum 4k "2 1 !-5 program should write 2 But it not only give me wrong answer, but also doesn't read all my input. When I write:
java GiveMeSum 4 2 1 -5
4 5 4 5 4 5 4 5
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at GiveMeSum.main(GiveMeSum.java:12)
public class GiveMeSum {
public static void main(String[] args) throws IOException {
int sum = 0;
Scanner sc = new Scanner(System.in).useDelimiter("(\\D|^-)");
for ( int i = 0; i < args.length; i++) {
sum += sc.nextInt();
}
System.out.println(sum);
}
}
Also there wasn't that exception. It's just showed up suddenly