Task 3 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

6.1 Scanner — reading lines and splitting

Lesson

Reading whole lines

nextLine() reads an entire line — everything up to the next line break — as a String, and hasNextLine() reports whether another line is waiting. To break a line into pieces, use line.split(",") (or another separator); split returns a String[]. Convert a numeric piece to an int with Integer.parseInt(piece).


Worked example

String line = "Ada,17,true";
String[] parts = line.split(",");
System.out.println(parts[0]);   // Ada
System.out.println(parts[1]);   // 17

split(",") breaks the line at each comma, giving the array {"Ada", "17", "true"}.


A common trap

After nextInt(), the line break stays in the buffer, so an immediate nextLine() reads an empty String instead of the next real line. The fix is to call an extra nextLine() to consume the leftover break:

int n = sc.nextInt();
sc.nextLine();               // consume the leftover line break
String name = sc.nextLine(); // now reads the real next line

▶ Try it: run this, type one comma-separated line (like apple,banana,cherry) into the input box, and see it split into parts.



Which method reads an entire line as a String?


"a,b,c".split(",") returns...


Type exactly what this program prints for the input shown.

Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
String[] parts = line.split(",");
int sum = 0;
for (int i = 0; i < parts.length; i++) {
    sum = sum + Integer.parseInt(parts[i]);
}
System.out.println(sum);

Input: 2,4,6,8


Right after calling nextInt(), calling nextLine() usually reads...


True or false?