Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Basics Getting Started with Java Strings and Variables

abmsc86
abmsc86
4,949 Points

Playing around with two %s in one line. Need help!

Hello peeps!

I was playing around with the codes and I happen to stumble on a problem. I wrote:

    String firstName = "Bryan";
    // thisIsAnExampleOfCamelSpacing
    console.printf("Hello, my name is %s.\n", firstName);
    console.printf("Hello, I am %s and I am learning Java. %s is awesome!\n", firstName);

The first line of code works, but the second line shows an error after running "java" command. Does this have something to do with two %s in a line? If so, does anyone know how to fix the code with two %s in a line? Or should I separate the two %s in a line?

2 Answers

Seth Kroger
Seth Kroger
56,407 Points

You can pass more that one variable in to printf to be substituted into the string. Each % formatter in the string is replaced by the next variable in the argument list by default. You can change that order as outlined here: https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#dpos You can see format strings can get a lot more complicated that the simple ones here in this course.

//  Both these will work, as well as passing firstName twice.
console.printf("Hello, I am %s and I am learning Java. %<s is awesome!\n", firstName);
//                                                      ^-- selects the previous agrument
console.printf("Hello, I am %1$s and I am learning Java. %1$s is awesome!\n", firstName);
//                                                        ^-- selects the first agrument

You have two %s so you'll need to supply two String arguments.

If you want firstName to appear twice, you can do ("... %s ... %s ... ", firstName, firstName)