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

Multiple questions ?

So i was wondering how to get more than one question(answers) printed into one line, here is what i done to the code :

import java.io.Console;

public class Introductions {

    public static void main(String[] args) {
        Console console = System.console();
        // Welcome to the Introductions program!  Your code goes below here
      String firstName = console.readLine("What is your name? ");
      String lastName = console.readLine("What is your surname? ");
        console.printf("My name is %s %2$s\n", firstName, lastName);
      console.printf("%s %2$s is learning how to write Java\n", firstName, lastName);

2 Answers

Hi there,

If you want to interpolate more than one variable into your string formatter, you just need to add the relevant number of insertion points, like %s for a string. You then list your variable names in the order you want them inserting:

console.printf("%s %s is learning how to write Java\n", firstName, lastName);

The first %s will have the value held within firstName inserted there and the second %s will have the value held in the second variable, lastName`, inserted.

You can insert lots of differnet variable types; not just strings. There's a table here that can help you with that.

Make sense?


There are two options. 1. is easy and straight forward. Instead of asking 2 questions you ask 1.

String fullname = console.readLine("What is your firstname and lastname? ");
console.printf("My name is %s\n", fullname );
  console.printf("%s is learning how to write Java\n", fullname );
  1. is you split strings which can be unreliable and you will have to handle exceptions or mistypes like if the user types "JohnD oe" instead of "John Doe". That makes his Last name "oe" and first "JohnD". That is if you split strings.

Use #1 and forget #2