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 trial

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,413 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)