Question

I'm trying to skip a line using an escape sequence, my code looks like

System.out.printf("Number of students: " + numberOfStudents "\n");

but I am getting an error which says "Syntax error on token ""\n"", delete this token"

I get the same error when trying

System.out.printf("Number of students: %c", numberOfStudents "\n");

This code works but I'm trying to understand what I did wrong

System.out.printf("Number of students: %d \n", numberOfStudents );

Is there a rule against using escape sequences after referencing a variable?

Thanks

Was it helpful?

Solution

This:

numberOfStudents "\n"

isn't valid. You've got two tokens there - an identifier and a string literal - with just a space between them. That's not valid. You could use concatenation:

System.out.printf("Number of students: " + numberOfStudents + "\n");

if you want... but you can't just put the string literal at the end like that.

I would suggest that your final code is the cleanest anyway, although I'd remove the space before the line break. Another alternative would be to let println put the line break on for you:

System.out.println("Number of students: " + numberOfStudents);

OTHER TIPS

You just forgot the + in between numberOfStudents and "\n":

System.out.printf("Number of students: " + numberOfStudents + "\n");

There must be a + operator between everything you want to concatenate, just like you wouldn't say 1 + 2 3 in math.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top