Home > front end >  Adding whitespace in Java zyBooks
Adding whitespace in Java zyBooks

Time:04-29

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.

CodePudding user response:

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);

CodePudding user response:

I don't know about why it should be bad practise. I mean that's litteraly what you want - to have two spaces, one after "Hello" and one before "and", but there is, in fact, better way to achive this. By using formating you'll have only one string with one parameter.

System.out.printf("Hello %s and welcome to CS Online!\n", user.name);
  • Related