Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialLearning coding
Front End Web Development Techdegree Student 9,937 PointsWhy isn't this code working?
Hi,
I would like to use the escape sequence \n in order to have the firstName and the lastName on different lines in the output. That looks cleaner, but I get errors from the console when I try to use the escape sequence.
import java.io.Console;
public class Introductions {
public static void main(String[] args) {
Console console = System.console();
String firstName = console.readLine("Enter your first name: "); String lastName = console.readLine("Enter your last name: "); console.printf("First name: %s", firstName\n"); console.printf("Last name: %s", lastName\n"); } }
3 Answers
Eva Kadar
8,272 PointsHi Rene,
the \n should be between the %s and the apostrophe and you don't need the apostrophe after it either.
Try something like this:
import java.io.Console;
public class Introductions {
public static void main(String[] args) {
Console console = System.console();
String firstName = console.readLine ("Enter your first name: ");
String lastName = console.readLine ("Enter your last name: ");
console.printf("First name: %s %n", firstName);
console.printf("Last name: %s %n", lastName);
}
}
Learning coding
Front End Web Development Techdegree Student 9,937 PointsThanks, that works. But why do you use %n instead of \n?
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 PointsThe %n is a platform-independent newline character
Quote from docs
https://docs.oracle.com/javase/tutorial/java/data/numberformat.html
Craig will start using it at some point and give some explanation as well, just follow along the Java Track
Eva Kadar
8,272 PointsYou can use both, it means the same, I just prefer the %n - and yes, Craig starts to use it as well. Anyway, its up to you I think. :)