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, Variables, and Formatting

Anurag Gracian
Anurag Gracian
315 Points

i do not know why my string variable is not working

i defined the string variable. but the code is not working

Name.java
// I have setup a java.io.Console object for you named console
String firstName = "Anurag";
  console.printf("%s\n, firstName");

 }
}

1 Answer

Hey there Anurag!

Your code is almost perfect.

The console.printf() function requires one extra argument for every formatter you pass into it. Take this as an example:

console.printf("%s %s %s %s");
//This will throw an error.

You have 4 string formatters, which means you must have 4 strings (either as literals or variables) passed into the method.

The code, when properly written, would look like this:

String one = "one";
String two = "two";
String three = "three";
String four = "four";

console.printf("%s %s %s %s", one, two, three, four);
//The console will display: one two three four

For your code specifically, you need to remove "firstName" from the string and rewrite it like so:

// I have setup a java.io.Console object for you named console
String firstName = "Anurag";
  console.printf("%s\n", firstName);

 }
}

This is telling the printf() function that you have a string ("%s\n") with one variable/literal being passed into it (firstName).

Hopefully this helps. :-)