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
This happens because you pass "4 2 1 -5" not as input but as arguments so they come into args
parameter of the main
method. To pass them as input wait till the app starts and enter them or use input stream redirection
Update (code for arguments processing)
How should I write it in java to take input as arguments then? Is there a specific easy way?
I'd say that using arguments for non-fixed number of input params is not so good idea. I'd still say that using input stream is the way to go - this is what it was designed for! Also your parsing requirements are a bit umbigious. Still here is my attempt
public class Main
{
static OptionalInt parseOnlyInt(String s)
{
String digitsOnly = s.replaceAll("[^0-9]", "");
if (digitsOnly.length() == 0)
return OptionalInt.empty();
else
return OptionalInt.of(Integer.parseInt(digitsOnly));
}
public static void main(String[] args)
{
int sum = Arrays.stream(args)
.map(Main::parseOnlyInt)
// probably in Java 9 OptionalInt::stream would be better than next 2 lines
// see https://bugs.openjdk.java.net/browse/JDK-8050820
.filter(OptionalInt::isPresent)
.mapToInt(OptionalInt::getAsInt)
.sum();
System.out.println(Arrays.toString(args));
System.out.println(sum);
}
}
Or if you prefer the old (non-Java-8) way here it is
public static void main(String[] args)
{
int sum = 0;
for (int i = 0; i < args.length; i++)
{
String digitsOnly = args[i].replaceAll("[^0-9]", "");
if (digitsOnly.length() != 0)
sum += Integer.parseInt(digitsOnly);
}
System.out.println(Arrays.toString(args));
System.out.println(sum);
}