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

MOHD AMIRUN AQMAR BIN ROSLAN
MOHD AMIRUN AQMAR BIN ROSLAN
77 Points

Not understand

I wrote String myName="Ben" but it still writtten error. That wwhy i dont understand

Name.java
// I have setup a java.io.Console object for you named console
String myName="Ben"
  Console.print("Hello,my name is Ben/n)

1 Answer

Hey Mohd,

You've correctly declared your String variable (Other than missing a semicolon). However, your print line needs some work.

For this prompt, particularly the second and third, you're tasked with using the printf method on the console object. Your code should print to the console, "[YOUR NAME] can code in Java!"

So, it should look like this:

String firstName = "Jacob";
console.printf("%s can code in Java!", firstName);

However, let's also look at your code:

String myName = "Ben";
console.printf("Hello, my name is %s \n", myName);

First, instead of just typing your name or any text, you can use %s, which will print whatever is stored in the myName variable as long as it is a String. There are other methods you'll learn through the course to format numbers, etc. But for this challenge, the focus is just on formatting Strings. Lastly, if you want to create a new line, use \n.

Hope this helps a bit.

Best,

Jacob

In short, without giving a variable name, %s will have no clue what String variable you want to print.

Take a look at this example without any other distractions:

String example = "Example"; 
console.printf("%s", example); 

This will print the text "Example" to the console, as the String variable example has the text, "Example" stored inside.

However, this is only if you are using printf. If you're just looking to print to the console without formatting any Strings or numbers, you can use println.

String myName = "Ben";
console.println("Hello, my name is " + myName); //Using a stored variable
console.println("Hello, my name is Ben."); //Without using a stored variable

But for this specific challenge, the prompt is asking you to use printf.

Does this makes sense?

Best,

Jacob

I hope this makes sense. If I explained it poorly, I apologize.

Best,

Jacob