import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
while (true) {
System.out.print("Please enter a number: ");
int num = scanner.nextInt();
if (num % 2 == 0) {
sum += num;
System.out.println("sum = " + sum);
continue;
}
scanner.nextLine(); // this line
System.out.print("Do you want to continue?(Y/N): ");
String response = scanner.nextLine();
if (response.toLowerCase().charAt(0) == 'n') {
break;
}
}
System.out.println("Total sum = " + sum);
}
}
Above can run; my question is, if I delete the line with comment: scanner.nextLine()
Why it gives error: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0