Search code examples
javawhitespace

Adding whitespace in Java zyBooks


Here's what I have right now:

import java.util.Scanner;

public class Welcome {
   public static void main(String[] args) {
      // Complete this statement to create a new instance of Scanner passing in System.in
      Scanner scan = new Scanner(System.in);

      // Complete this statement to use the scanner object to read a string from the user
      String user_name = scan.next();
  
      // Add the statement to print the desired output
      System.out.println("Hello" + user_name + "and welcome to CS Online!");
  
   }
}

If user name = Joe, this outputs: HelloJoeand welcome to CS Online! I fixed it by putting a space after "Hello" and a space before "and" like this:

System.ou.println("Hello " + user name + " and welcome to CS Online!");

My question is, is there a better way to add whitespace between the variable and strings? The way I did it doesn't seem like good practice.


Solution

  • You can use System.out.printf (immediately prints) or String.format (returns result in a String) instead which lets you use only a single String with a placeholder value that gets replaced by a variable, %s is the placeholder for a String variable.

    This can be especially useful when you have multiple variables you want to print inside of a String.

    String userName = scan.next();
    System.out.printf("Hello %s and welcome to CS Online!", userName);
    

    Note that I also changed user_name to userName to follow proper Java naming conventions of camelCasing as you were asking about good practices.

    Here is an example with multiple variables:

    String firstName = scan.next();
    String lastName = scan.next();
      
    System.out.printf("Hello my first name is %s and my last name is %s!", firstName, lastName);