#nextLine() issue -- beginner

1 messages · Page 1 of 1 (latest)

dark cloud
#
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

chrome walrusBOT
#

This post has been reserved for your question.

Hey @dark cloud! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

shy holly