This is a program that asks for user input (number) and prints a sum statement. Which continually works until user enters END. It works fine, however when a negative integer is inputted, an empty print statement is returned. Any help or insight into how to include negative integers in the sum is greatly appreciated thanks for your time!
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int sum = 0;
String val = "";
while (val.equals(""))
{
System.out.print("Enter a number: ");
val = scan.nextLine();
if (val.equalsIgnoreCase("end")) {
break;
}
else if (val.matches("\\d+")) {
sum += Integer.parseInt(val);
System.out.println("Sum is now: " + sum);
}
else {
System.err.println("");
}
val = "";
}
}
}
This would be because \\d+
picks up one or more numbers. Whereas the -
before a negative number is not considered a number so therefore it does not match your regex.
Try using something like:
-?\\d+